我试图将报告写入文本文件。当我使用print
方法时,一切看起来都没问题,但在文件中没有写任何内容。这是我的代码。
public void writeFile(String filename,String report){
try{
FileWriter fw=null;
try{
fw = new FileWriter(filename);
fw.write("The game report \n");
fw.write(report);
fw.write("Hope everyone has enjoyed it");
fw.flush();
}
catch(FileNotFoundException e){
System.out.println(filename +"not found");
System.exit(0);
}
finally{
try{
fw.close();
}
catch( Exception exp){
System.out.println("Problem closing the filewriter");
}
}
}
catch(IOException e) {
e.printStackTrace();
System.exit(1);
}
}
这是主方法的代码。
public class MainDarts {
public static void main(String[] args) {
GameManager manager = new GameManager();
manager.readFile("Data.csv");
manager.Execute();
String report = manager.getOverallReport();
manager.writeFile("OutputData.txt", report);
}
}
答案 0 :(得分:1)
像这样使用PrintWriter类
PrintWriter writer = new PrintWriter("filename.txt", "UTF-8");
writer.println("Hello");
writer.flush();
writer.close();
答案 1 :(得分:0)
或者您可以考虑更简单的事情
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filename))) {
writer.write(report);
}
或
Files.write(Paths.get(filename), report.getBytes());