我正在尝试为我正在处理的程序创建一个save函数,但由于某种原因,每当我运行它时,它都只能通过try{}语句的第一行。我的代码如下所示。
public void saveGame() {
System.out.println("saveGame");
try
{
System.out.println("try saveGame");
BufferedWriter b = new BufferedWriter(new FileWriter("chardata.txt"));
System.out.println("try saveGame2");
String sp = System.getProperty("line.separator");
System.out.println("try saveGame3");
b.write("Miscellaneous char data here");
b.close();
}
catch(IOException ex)
{
System.out.println("File Writing Error");
}
}当我运行这个程序时,只打印出"saveGame“和"try saveGame”这两行。也没有“文件写入错误”,它只是在"try saveGame“行之后不做任何事情。我不确定这是否相关,但我是在一所学校的计算机上执行此操作的,该计算机可能具有受限权限。任何形式的解释和/或帮助都将不胜感激。
发布于 2014-01-28 21:20:48
我认为编写文件的更好方法是使用FileOutputStream和OutputStreamWriter。此外,您应该将b.close移到finally语句中,因为如果在执行该b.close之前抛出异常,它将永远不会被执行。
public void saveGame() {
System.out.println("saveGame");
try
{
System.out.println("try saveGame");
String path = "./chardata.txt"; //your file path
File file = new File(path);
FileOutputStream fsal = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fsal);
Writer w = new BufferedWriter(osw);
System.out.println("try saveGame2");
String sp = System.getProperty("line.separator");
System.out.println("try saveGame3");
w.write("Miscellaneous char data here");
}
catch(IOException ex)
{
System.out.println("File Writing Error");
}
finally{
if(w!=null)
w.close();
}
}https://stackoverflow.com/questions/21406387
复制相似问题