วิธีอ่านไฟล์ใน Java

1. ภาพรวม

ในการกวดวิชานี้เราจะสำรวจวิธีการที่แตกต่างกันไปอ่านจากไฟล์ในจาวา

ขั้นแรกเราจะดูวิธีโหลดไฟล์จาก classpath, URL หรือจากไฟล์ JAR โดยใช้คลาส Java มาตรฐาน

ประการที่สองเราจะเห็นวิธีการอ่านเนื้อหาที่มีBufferedReader , สแกนเนอร์ , StreamTokenizer , DataInputStream , SequenceInputStream,และFileChannel นอกจากนี้เราจะพูดถึงวิธีการอ่านไฟล์ที่เข้ารหัส UTF-8

สุดท้ายนี้เราจะสำรวจเทคนิคใหม่ในการโหลดและอ่านไฟล์ใน Java 7 และ Java 8

บทความนี้เป็นส่วนหนึ่งของซีรี่ส์“ Java - Back to Basic” ใน Baeldung

2. การตั้งค่า

2.1 ไฟล์อินพุต

ในตัวอย่างส่วนใหญ่ในบทความนี้เราจะอ่านไฟล์ข้อความที่มีชื่อไฟล์fileTest.txtซึ่งมีหนึ่งบรรทัด:

Hello, world!

ในบางตัวอย่างเราจะใช้ไฟล์อื่น ในกรณีเหล่านี้เราจะกล่าวถึงไฟล์และเนื้อหาอย่างชัดเจน

2.2 วิธีการช่วยเหลือ

เราจะใช้ชุดตัวอย่างการทดสอบโดยใช้คลาส Java หลักเท่านั้นและในการทดสอบเราจะใช้การยืนยันโดยใช้ Hamcrest matchers

การทดสอบจะแบ่งปันวิธีreadFromInputStreamทั่วไปที่แปลงInputStreamเป็นStringเพื่อให้ยืนยันผลลัพธ์ได้ง่ายขึ้น:

private String readFromInputStream(InputStream inputStream) throws IOException { StringBuilder resultStringBuilder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = br.readLine()) != null) { resultStringBuilder.append(line).append("\n"); } } return resultStringBuilder.toString(); }

โปรดทราบว่ามีวิธีอื่นในการบรรลุผลลัพธ์เดียวกัน คุณสามารถอ่านบทความนี้สำหรับทางเลือกอื่น ๆ

3. การอ่านไฟล์จาก Classpath

3.1. ใช้ Standard Java

ส่วนนี้จะอธิบายวิธีการอ่านไฟล์ที่มีอยู่ใน classpath เราจะอ่าน“ fileTest.txt ” ที่มีอยู่ในsrc / main / resources :

@Test public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() { String expectedData = "Hello, world!"; Class clazz = FileOperationsTest.class; InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt"); String data = readFromInputStream(inputStream); Assert.assertThat(data, containsString(expectedData)); }

ในข้อมูลโค้ดด้านบนเราใช้คลาสปัจจุบันเพื่อโหลดไฟล์โดยใช้เมธอดgetResourceAsStreamและส่งผ่านพา ธ สัมบูรณ์ของไฟล์เพื่อโหลด

วิธีการเดียวกันนี้มีอยู่ในอินสแตนซ์ClassLoaderเช่นกัน:

ClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("fileTest.txt"); String data = readFromInputStream(inputStream);

เราขอรับclassLoaderของชนชั้นปัจจุบันใช้getClass (). getClassLoader ()

ความแตกต่างที่สำคัญคือเมื่อใช้getResourceAsStreamบนอินสแตนซ์ClassLoaderพา ธ จะถือว่าเป็นค่าสัมบูรณ์โดยเริ่มจากรูทของคลาสพา ธ

เมื่อนำมาใช้กับชั้นเช่น,เส้นทางที่อาจจะเทียบกับแพคเกจหรือเส้นทางที่แน่นอนซึ่งเป็นทำนองโดยเฉือนชั้นนำ

แน่นอนโปรดทราบว่าในทางปฏิบัติควรปิดสตรีมแบบเปิดเสมอเช่นInputStreamในตัวอย่างของเรา:

InputStream inputStream = null; try { File file = new File(classLoader.getResource("fileTest.txt").getFile()); inputStream = new FileInputStream(file); //... } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }

3.2. การใช้commons-io Library

ตัวเลือกทั่วไปอีกตัวหนึ่งคือการใช้คลาสFileUtilsของแพ็คเกจcommons-io :

@Test public void givenFileName_whenUsingFileUtils_thenFileData() { String expectedData = "Hello, world!"; ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("fileTest.txt").getFile()); String data = FileUtils.readFileToString(file, "UTF-8"); assertEquals(expectedData, data.trim()); }

ที่นี่เราผ่านไฟล์วัตถุกับวิธีการreadFileToString ()ของFileUtilsระดับ คลาสยูทิลิตี้นี้จัดการโหลดเนื้อหาโดยไม่จำเป็นต้องเขียนโค้ดสำเร็จรูปใด ๆ เพื่อสร้างอินสแตนซ์InputStreamและอ่านข้อมูล

ห้องสมุดเดียวกันยังมีIOUtilsชั้น:

@Test public void givenFileName_whenUsingIOUtils_thenFileData() { String expectedData = "Hello, world!"; FileInputStream fis = new FileInputStream("src/test/resources/fileTest.txt"); String data = IOUtils.toString(fis, "UTF-8"); assertEquals(expectedData, data.trim()); }

ที่นี่เราส่งผ่านวัตถุFileInputStreamไปยังเมธอดtoString ()ของคลาสIOUtils คลาสยูทิลิตี้นี้จัดการโหลดเนื้อหาโดยไม่จำเป็นต้องเขียนโค้ดสำเร็จรูปใด ๆ เพื่อสร้างอินสแตนซ์InputStreamและอ่านข้อมูล

4. การอ่านด้วยBufferedReader

ตอนนี้เรามาดูวิธีต่างๆในการแยกวิเคราะห์เนื้อหาของไฟล์

เราจะเริ่มต้นด้วยวิธีง่ายๆในการอ่านจากไฟล์โดยใช้BufferedReader:

@Test public void whenReadWithBufferedReader_thenCorrect() throws IOException { String expected_value = "Hello, world!"; String file; BufferedReader reader = new BufferedReader(new FileReader(file)); String currentLine = reader.readLine(); reader.close(); assertEquals(expected_value, currentLine); }

โปรดทราบว่าreadLine ()จะคืนค่า nullเมื่อถึงจุดสิ้นสุดของไฟล์

5. การอ่านจากไฟล์โดยใช้ Java NIO

ใน JDK7 แพ็คเกจ NIO ได้รับการอัพเดตอย่างมาก

ดู Let 's ตัวอย่างโดยใช้ที่ไฟล์ระดับและreadAllLinesวิธี readAllLinesวิธีการยอมรับเส้นทาง

คลาสพา ธถือได้ว่าเป็นการอัพเกรดjava.io ไฟล์ที่มีการดำเนินการเพิ่มเติมบางอย่าง

5.1. การอ่านไฟล์ขนาดเล็ก

รหัสต่อไปนี้แสดงวิธีการอ่านไฟล์ขนาดเล็กโดยใช้คลาสไฟล์ใหม่:

@Test public void whenReadSmallFileJava7_thenCorrect() throws IOException { String expected_value = "Hello, world!"; Path path = Paths.get("src/test/resources/fileTest.txt"); String read = Files.readAllLines(path).get(0); assertEquals(expected_value, read); }

Note that you can use the readAllBytes() method as well if you need binary data.

5.2. Reading a Large File

If we want to read a large file with Files class, we can use the BufferedReader:

The following code reads the file using the new Files class and BufferedReader:

@Test public void whenReadLargeFileJava7_thenCorrect() throws IOException { String expected_value = "Hello, world!"; Path path = Paths.get("src/test/resources/fileTest.txt"); BufferedReader reader = Files.newBufferedReader(path); String line = reader.readLine(); assertEquals(expected_value, line); }

5.3. Reading a File Using Files.lines()

JDK8 offers the lines() method inside the Files class. It returns a Stream of String elements.

Let’s look at an example of how to read data into bytes and decode using UTF-8 charset.

The following code reads the file using the new Files.lines():

@Test public void givenFilePath_whenUsingFilesLines_thenFileData() { String expectedData = "Hello, world!"; Path path = Paths.get(getClass().getClassLoader() .getResource("fileTest.txt").toURI()); Stream lines = Files.lines(path); String data = lines.collect(Collectors.joining("\n")); lines.close(); Assert.assertEquals(expectedData, data.trim()); }

Using Stream with IO channels like file operations, we need to close the stream explicitly using the close() method.

As we can see, the Files API offers another easy way to read the file contents into a String.

In the next sections, let's have a look at other, less common methods of reading a file, that may be appropriate in some situations.

6. Reading with Scanner

Next, let's use a Scanner to read from the File. Here, we'll use whitespace as the delimiter:

@Test public void whenReadWithScanner_thenCorrect() throws IOException { String file = "src/test/resources/fileTest.txt"; Scanner scanner = new Scanner(new File(file)); scanner.useDelimiter(" "); assertTrue(scanner.hasNext()); assertEquals("Hello,", scanner.next()); assertEquals("world!", scanner.next()); scanner.close(); }

Note that the default delimiter is the whitespace, but multiple delimiters can be used with a Scanner.

The Scanner class is useful when reading content from the console, or when the content contains primitive values, with a known delimiter (eg: a list of integers separated by space).

7. Reading with StreamTokenizer

Next, let's read a text file into tokens using a StreamTokenizer.

The way the tokenizer works is – first, we need to figure out what the next token is – String or number; we do that by looking at the tokenizer.ttype field.

Then, we'll read the actual token based on this type:

  • tokenizer.nval – if the type was a number
  • tokenizer.sval – if the type was a String

In this example we'll use a different input file which simply contains:

Hello 1

The following code reads from the file both the String and the number:

@Test public void whenReadWithStreamTokenizer_thenCorrectTokens() throws IOException { String file = "src/test/resources/fileTestTokenizer.txt"; FileReader reader = new FileReader(file); StreamTokenizer tokenizer = new StreamTokenizer(reader); // token 1 tokenizer.nextToken(); assertEquals(StreamTokenizer.TT_WORD, tokenizer.ttype); assertEquals("Hello", tokenizer.sval); // token 2 tokenizer.nextToken(); assertEquals(StreamTokenizer.TT_NUMBER, tokenizer.ttype); assertEquals(1, tokenizer.nval, 0.0000001); // token 3 tokenizer.nextToken(); assertEquals(StreamTokenizer.TT_EOF, tokenizer.ttype); reader.close(); }

Note how the end of file token is used at the end.

This approach is useful for parsing an input stream into tokens.

8. Reading with DataInputStream

We can use DataInputStream to read binary or primitive data type from a file.

The following test reads the file using a DataInputStream:

@Test public void whenReadWithDataInputStream_thenCorrect() throws IOException { String expectedValue = "Hello, world!"; String file; String result = null; DataInputStream reader = new DataInputStream(new FileInputStream(file)); int nBytesToRead = reader.available(); if(nBytesToRead > 0) { byte[] bytes = new byte[nBytesToRead]; reader.read(bytes); result = new String(bytes); } assertEquals(expectedValue, result); }

9. Reading with FileChannel

If we are reading a large file, FileChannel can be faster than standard IO.

The following code reads data bytes from the file using FileChannel and RandomAccessFile:

@Test public void whenReadWithFileChannel_thenCorrect() throws IOException { String expected_value = "Hello, world!"; String file = "src/test/resources/fileTest.txt"; RandomAccessFile reader = new RandomAccessFile(file, "r"); FileChannel channel = reader.getChannel(); int bufferSize = 1024; if (bufferSize > channel.size()) { bufferSize = (int) channel.size(); } ByteBuffer buff = ByteBuffer.allocate(bufferSize); channel.read(buff); buff.flip(); assertEquals(expected_value, new String(buff.array())); channel.close(); reader.close(); }

10. Reading a UTF-8 Encoded File

Now, let's see how to read a UTF-8 encoded file using BufferedReader. In this example, we'll read a file that contains Chinese characters:

@Test public void whenReadUTFEncodedFile_thenCorrect() throws IOException { String expected_value = "青空"; String file = "src/test/resources/fileTestUtf8.txt"; BufferedReader reader = new BufferedReader (new InputStreamReader(new FileInputStream(file), "UTF-8")); String currentLine = reader.readLine(); reader.close(); assertEquals(expected_value, currentLine); }

11. Reading Content from URL

To read content from a URL, we will use “/” URL in our example as:

@Test public void givenURLName_whenUsingURL_thenFileData() { String expectedData = "Baeldung"; URL urlObject = new URL("/"); URLConnection urlConnection = urlObject.openConnection(); InputStream inputStream = urlConnection.getInputStream(); String data = readFromInputStream(inputStream); Assert.assertThat(data, containsString(expectedData)); }

There are also alternative ways of connecting to a URL. Here we used the URL and URLConnection class available in the standard SDK.

12. Reading a File from a JAR

To read a file which is located inside a JAR file, we will need a JAR with a file inside it. For our example we will read “LICENSE.txt” from the “hamcrest-library-1.3.jar” file:

@Test public void givenFileName_whenUsingJarFile_thenFileData() { String expectedData = "BSD License"; Class clazz = Matchers.class; InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt"); String data = readFromInputStream(inputStream); Assert.assertThat(data, containsString(expectedData)); }

Here we want to load LICENSE.txt that resides in Hamcrest library, so we will use the Matcher's class that helps to get a resource. The same file can be loaded using the classloader too.

13. Conclusion

As you can see, there are many possibilities for loading a file and reading data from it using plain Java.

You can load a file from various locations like classpath, URL or jar files.

จากนั้นคุณสามารถใช้BufferedReaderเพื่ออ่านทีละบรรทัดเครื่องสแกนเนอร์เพื่ออ่านโดยใช้ตัวคั่นที่แตกต่างกันStreamTokenizerเพื่ออ่านไฟล์ลงในโทเค็นDataInputStreamเพื่ออ่านข้อมูลไบนารีและชนิดข้อมูลดั้งเดิมSequenceInput Streamเพื่อเชื่อมโยงไฟล์หลายไฟล์เข้าในสตรีมเดียวFileChannelเพื่ออ่านได้เร็วขึ้น จากไฟล์ขนาดใหญ่ ฯลฯ

คุณสามารถค้นหาซอร์สโค้ดได้ใน repo GitHub ต่อไปนี้