此代码将字符串写入文件。关闭编写器很重要,所以这是在一个finally块中完成的。
public void writeLineToFile(String str) throws IOException {
File file = new File("file.txt");
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(file));
bw.write(str);
} finally {
if (bw != null) {
bw.close();
}
}
}另请注意,write(String s)在写入字符串后不要放置换行符。说白了就是使用newLine()方法。
Java 7 添加了java.nio.file包和try-with-resources:
public void writeLineToFile(String str) throws IOException {
Path path = Paths.get("file.txt");
try (BufferedWriter bw = Files.newBufferedWriter(path)) {
bw.write(str);
}
}