1. Java8 file processing
Use the Java8 java.nio.file
method for file processing.
1.1. Reading files
All content is read out at once, and the result is a string.
1.1.1. Code
/**
* 读取文件
*
* @param path 文件路径
* @return 文件内容(字符串)
*/
public static String read(String path) {
try {
return Files.readString(Paths.get(path));
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
1.1.2. Calling
// 文件放在项目根目录下的 config 目录下,此处填写的是相对路径
String json = FileUtils.read("config/user.json");
System.out.println(json);
The file path is generally represented
正斜杠 “/”
by , which can better adapt to Windows and Linus systems.
1.1.3. Running results
1.1.4. The file path uses an absolute path
Files can be read using absolute addresses. However, in the project, try not to use the absolute address to read the file, because the installation path may change when the project goes online.
Here's an example of using an absolute path:
String json = FileUtils.read("F:/open-source/spring-demo/GsonDemo/config/user.json");
System.out.println(json);
2. File tools
package com.example.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileUtils {
/**
* 读取文件
*
* @param path 文件路径
* @return 文件内容(字符串)
*/
public static String read(String path) {
try {
return Files.readString(Paths.get(path));
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}