利用Java的BufferedWriter和BufferedReader读写文件。读文件时可以利用readline直接读取一行。
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.FileReader;
public class FileReadWrite {
public static void main(String[] args) throws Exception {
writeFileContents("hello world","./file.txt");
String result = readFileContents("./file.txt");
System.out.println(result);
}
private static void writeFileContents(String text, String file) throws Exception {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write(text);
}
}
private static String readFileContents(String file) throws Exception {
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
return sb.toString();
}
}
}