Java 8 method of reading files

JDK7 introduces a new file operation class java nio. file. File, which contains many useful methods to manipulate files, such as checking whether the file is hidden or read-only. Developers can also use files The readallbytes (path) method reads the entire file into memory. This method returns a byte array. It can also pass the result to the constructor of string to create string output.

This method ensures that the file property is closed when all bytes of the file are read in, otherwise IO exceptions or other unchecked exceptions will occur. This means that there is no need to close the file after reading the last block of the file. Note that this method is not suitable for reading large files because there may be insufficient memory space. Developers should also specify the character encoding of the file to avoid any exceptions or parsing errors.

If you want to read the file as a string, you can also use the readalllines (path path, charset CS) method. This method is similar to the previous method, and there is no need to close the file after reading the file. But it returns not a byte array, but a string array. Moreover, Java 8 rewrites this method and directly uses UTF-8 encoding for string conversion without specifying a character set. If you want to read in files as strings line by line, you can use files Lines () method, which returns a character stream from the read file and converts bytes into characters using UTF-8 encoding. Using the foreach () method, you can output all the contents of the file to the console with only one line of Java code, as shown in the third code fragment below.

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
 
public class FileReadingTest {
 public static void main(String[] args) throws IOException {
  // Java 7 例子
  // Files.readAllBytes默认以UTF-8编码读入文件,故文件的编码如果不是UTF-8,那么中文内容会出现乱字符
  System.out.println(new String(Files.readAllBytes(Paths.get("D:\\jd.txt"))));
   // Java 8例子
  List<string> lines = Files.readAllLines(Paths.get("D:\\jd.txt"), StandardCharsets.UTF_8);
  StringBuilder sb = new StringBuilder();
  for(String line : lines){
   sb.append(line);
  }
  String fromFile = sb.toString();
        System.out.println(fromFile);
 
 }
}</string>

If you use jdk8 instead of JDK7, you can read the file in one line of code.

import static java.lang.System.out;
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
 
import java.io.IOException;
public class FileIntoString {
 public static void main(String[] args) throws IOException {
  // 一行代码搞定读文件,默认是UTF-8编码
  out.println(new String(readAllBytes(get("d:/jd.txt"))));
 }
}

If you use jdk8, you can also use the stream API to read and write files, so that the code is more concise and efficient. In the following example, the lines () method returns a character stream, and the string is encoded in UTF-8. As follows:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
 
 
public class Java8FileReader {
 public static void main(String[] args) throws IOException {
  // Java8用流的方式读文件,更加高效
  Files.lines(Paths.get("D:\\jd.txt"), StandardCharsets.UTF_8).forEach(System.out::println);
 }
}

The above example should pay attention to the following points:

1) the file may be large and may exceed the memory space, so it should be evaluated before use.

2) to output a log, record why the file cannot be read or any errors encountered when reading the file.

3) character encoding should be specified when converting bytes into characters.

4) deal with the situation that the file does not exist.

Also note that if the code of the read file is ANSI, the above example will report Java. Java when reading the file content nio. charset. Malformedinputexception: input length = 1 error.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>