读书人

FileWriter 写完资料用System.exit(

发布时间: 2013-09-27 14:23:42 作者: rapoo

FileWriter 写完文件,用System.exit(0);文件就被删除了
如题,先调用writeToIniFile,其中先删除这个文件,再重新写。问题是只要一执行到System.exit(0)刚写的文件就被删除了,什么原因?


public void writeToIniFile() throws IOException {
System.out.println("start to write info into news.ini");

String newsIni = USBConfig.drivePath + USBConfig.INIT_NEW_FOLDER + "\\news.ini";
File f = new File(newsIni);
if(f.exists()){
f.delete();
}
f.createNewFile();
int sum = this.getnewsList().size();
List<String> lines = new ArrayList<String>();
lines.add("[news]");
lines.add("sum="+sum);
StringBuilder line = new StringBuilder("news");
for(int i=0; i < sum; i++){
News n = this.getnewsList().get(i);
line.append(i).append("=").append(n.content);
lines.add(line.toString());
line = new StringBuilder("news");
}
System.out.println("the lines in memory ===============");
for(String s : lines){
System.out.println(s);
}
System.out.println("the lines in memory ===============");

FileReaderUtils.writeToFile(lines, f);

}



public static void writeToFile(List<String> lines, File ff) throws IOException{
System.out.println("writeToFile function started.");
File f = new File(ff.getAbsolutePath());
f.createNewFile();
String encoding = code(f);
FileOutputStream fos = new FileOutputStream(f);
OutputStreamWriter writer = new OutputStreamWriter(fos,
encoding);
//FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(writer);
for(String s : lines){
//bw.append(s);
bw.write(s);
bw.newLine();
bw.flush();
}
bw.flush();
writer.flush();
fos.flush();
bw.close();
writer.close();
fos.close();
System.out.println("writeToFile function finished.");
}

------解决方案--------------------


去看看创建文件的API吧,有很多种的,你这创建的是临时文件。

也有可能是file没有close

都试下
[解决办法]
你程序有删除文件的地方吗?
比如判断是否存在,如果存在的话就删除了,然后再重新创建。
这里删除的时候要注意使用onDelete,不要使用onExistDelete。具体可以看API。

读书人网 >J2SE开发

热点推荐