我已经替换了许多字符串并输出了结果,现在正尝试将这些行写入文本文件。这就是我所做的。我创建了一个新文件:
File newfile = new File("/Users/Bill/Desktop/newfile.txt");
if (newfile.exists()) {
System.out.println("File exists");
} else {
newfile.createNewFile();
System.out.println("New file created");
}
然后我尝试将 System.out.println(lines[i]); 的结果写入创建的文件。
try {
WriteToFile newFile = new WriteToFile(newfile, true);
newFile.write(lines[i]);
// lines[i] is what I used to print out System.out.println(lines[i])
}
catch (IOException e) {
System.out.println("Error.");
}
不过,我没有得到我所期待的。有什么建议么?
写文件:
public class WriteToFile {
private String path;
private boolean append = false;
public WriteToFile(String filename) {
path=filename;
}
public WriteToFile(String filename, boolean appendfile){
path=filename;
append=appendfile;
}
public void write(String text) throws IOException {
FileWriter filewrite = new FileWriter(path, append);
PrintWriter print = new PrintWriter(filewrite);
print.printf("%s" + "%n", text);
print.close();
}
}