In my last article, I introduced you to 5 ways to create files and write file data. In this section, I introduce you to 6 ways to read data from files.

In addition, I have recorded a video for this article: Summary of the 6 ways Java reads data from files – Summary of Java IO Basics 2

  • Scanner(Java 1.5) Read data by row and read data by delimiter for String, Int, etc.
  • Files.linesTo return toStream(Java 8) Streaming data processing, read by line
  • Files.readAllLinesTo return toList<String>(Java 8)
  • Files.readStringRead,String(Java 11), file maximum 2G.
  • Files.readAllBytesRead,byte[](Java 7), file maximum 2G.
  • BufferedReader, the classic way (Java 1.1 -> Forever)

It can be said that each method has its own applicable scenarios, which are introduced in the following.

1.Scanner

The first method is Scanner. The API provided from JDK1.5 can read file data by line and by separator. It can read both String and basic data types such as Int and Long.

@test void testReadFile1() throws IOException {// File content: Hello World|Hello Zimug String fileName = "D:\\data\\test\\newFile4.txt"; Try (Scanner sc = new Scanner(new FileReader(fileName)) {while (sc.hasnextline ()) {// Read the String line = String sc.nextLine(); System.out.println(line); } } try (Scanner sc = new Scanner(new FileReader(fileName))) { sc.useDelimiter("\\|"); // delimiter while (sc.hasnext ()) {// Delimiter String STR = sc.next(); System.out.println(str); }} // sc.hasnextint (), hasNextFloat(), underlying data types, etc. / / file contents: 1 | 2 fileName = "D: \ \ data \ \ test \ \ newFile5 TXT". try (Scanner sc = new Scanner(new FileReader(fileName))) { sc.useDelimiter("\\|"); While (sc.hasnextint ()) {Int Int intValue = sc.nextint (); System.out.println(intValue); }}}Copy the code

The above method produces the following output:

Hello World|Hello Zimug
Hello World
Hello Zimug
1
2
Copy the code

2.Files.lines (Java 8)

If you need to process the contents of a data file line by line, this method is one I recommend. It is simple and uses Java 8 Stream to integrate file reading and file processing.

@Test void testReadFile2() throws IOException { String fileName = "D:\\data\\test\\newFile.txt"; Stream<String> lines = files.lines (paths.get (fileName)); Stream<String> lines = files.lines (paths.get (fileName)); Lines. forEach(ele -> {system.out.println (ele); }); }Copy the code

ForEach retrieves row data from a Stream without guarantee of order, but fast. If you want to process the rows of a file in order, you can use forEachOrdered data, but processing is less efficient.

Lines.foreachordered (system.out ::println);Copy the code

Parallel (), suitable for large files.

Lines.parallel ().foreachordered (system.out ::println);Copy the code

Can also keep the Stream < String > converts a List < String >, but should pay attention to this means that you will all the data at once loaded into memory, attention should be paid to Java. Lang. OutOfMemoryError

/ / into a List < String >, attention should be paid to Java. Lang. OutOfMemoryError: Java heap space List<String> collect = lines.collect(Collectors.toList());Copy the code

3.Files.readAllLines

This method is still provided for us by Java8. If we don’t need a Stream

and want to get a List

directly by reading the file line by line, we use the following method. The same problem: this means that you will all the data at once loaded into memory, attention should be paid to Java. Lang. OutOfMemoryError

@Test void testReadFile3() throws IOException { String fileName = "D:\\data\\test\\newFile3.txt"; / / into a List < String >, attention should be paid to Java. Lang. OutOfMemoryError: Java heap space List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8); lines.forEach(System.out::println); }Copy the code

4.Files.readString(JDK 11)

Starting with java11, we have a way to read one file at a time. Files should not exceed 2 gigabytes, and be careful of your server and JVM memory. This method is suitable for quickly reading small text files.

@Test void testReadFile4() throws IOException { String fileName = "D:\\data\\test\\newFile3.txt"; //String s = files.readString (paths.get (fileName)); //String s = files.readString (paths.get (fileName)); }Copy the code

5.Files.readAllBytes()

What if you don’t have JDK11 (readAllBytes() starts with JDK7) and still want to quickly read the contents of a file to String at once? The data is read as a binary array and then converted to String content. This method is suitable for reading small text files quickly if there is no JDK11.

@Test void testReadFile5() throws IOException { String fileName = "D:\\data\\test\\newFile3.txt"; Byte [] bytes = files.readallBytes (paths.get (fileName)); byte[] bytes = files.readallBytes (paths.get (fileName)); String content = new String(bytes, StandardCharsets.UTF_8); System.out.println(content); }Copy the code

6. Classic pipe flow

The last one is the classic pipe flow

@Test void testReadFile6() throws IOException { String fileName = "D:\\data\\test\\newFile3.txt"; Try (BufferedReader br = new BufferedReader(new FileReader(fileName))){String line; while ((line = br.readLine()) ! = null) { System.out.println(line); Try (BufferedReader br = files.newBufferedReader (paths.get (fileName))){String line; while ((line = br.readLine()) ! = null) { System.out.println(line); }}}Copy the code

This method can be used in combination in a flexible way by nesting pipeline flows. For example, if we want to read a Java Object from a file, we can use ObjectInputStream only if the data in the file is written by ObjectOutputStream.

try (FileInputStream fis = new FileInputStream(fileName);
     ObjectInputStream ois = new ObjectInputStream(fis)){
   ois.readObject();
} 
Copy the code

Welcome to my blog, where there are many fine collections

  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.

Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.

  • Spring Boot2.0 by Hand
  • Spring Security- JWT-OAUTH2
  • RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
  • “Actual SpringCloud Micro-service from Bronze to King”
  • VUE Series