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 a hidden file, or checking whether the file is a read-only file. Developers can also use the Files.readAllBytes(Path) method to read the entire file into memory. This method returns a byte array and can also pass the result to the String constructor to create string output. This method ensures that when all byte contents of the file are read, the file attributes are closed, otherwise an IO exception or other unchecked exceptions will occur. This means that after reading the file to the last block content, there is no need to close 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, which 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 an array of strings. Moreover, Java8 overrides this method, without specifying a character set, directly using UTF-8 encoding for string conversion.
If you want to read the file as a string line by line, you can use the Files.lines() method, which returns the string stream from the read file and converts the bytes into characters using UTF-8 encoding. Using the forEach() method, you can use only one line of Java code to output all the contents of the file to the console, such as the third code snippet below.
The code copy is as follows:
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 examples
// Files.readAllBytes reads the file in UTF-8 encoding by default. Therefore, if the file encoding is not UTF-8, then the Chinese content will have chaotic characters.
System.out.println(new String(Files.readAllBytes(Paths.get("D://jd.txt"))));
// 8 examples of Java
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);
}
}
If you are not using JDK7, but JDK8, then one line of code can complete the reading of the file.
The code copy is as follows:
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 {
// One line of code can be used to read the file, the default is UTF-8 encoding
out.println(new String(readAllBytes(get("d:/jd.txt"))));
}
}
If you use JDK8, you can also use the streaming API to read and write files, so that the code is more concise and efficient.
In the following example, the lines() method returns a string stream, and the string uses UTF-8 encoding. as follows:
The code copy is 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 {
// Java 8 uses streaming to read files, which is more efficient
Files.lines(Paths.get("D://jd.txt"), StandardCharsets.UTF_8).forEach(System.out::println);
}
}
A few points to note in the above example:
1) The file may be large and may exceed the memory space. Evaluation must be done before use.
2) To output the log, record why the file cannot be read or any errors encountered while reading the file.
3) When converting bytes into characters, character encoding should be specified.
4) To deal with the situation where the file does not exist.
Also note that if the code of the read file is ANSI encoding, the above example will report a java.nio.charset.MalformedInputException: Input length = 1 error when reading the file content.