我用java的filewriter 发现写不了字符串进文件里,但又没有报错

String dir= f.getAbsolutePath();
dir= dir.substring(0, dir.length()-4)+"_1.txt";
File fn= new File(dir);
try{
FileWriter out= new FileWriter(fn);
for(int p=0;p<text.size();p++){
String s=text.get(p);
out.write(s);
}
}catch(IOException e3){
textArea.append("生成密钥出错:"+e3+'\n');
}
在控制台输出是没问题的,文件也已经生成了

你没刷新流,你用FileWriter创建来一个输出流对象out,out.write(s)是把字符串s输进了流里,并没有输出到文件中,你必须调用out.flush()方法讲流中数据冲进目标文件,注意,io流用完后要记得用close()方法关闭,否则将有意想不到的麻烦,另外close()方法也具有flush()的作用。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-12-28
你好,因为是字符流所以要刷新,写一次后刷一次,在out.write(s);下面在写一行out.flush();
最后记得关闭流。out.close();

如果满意,请采纳,谢谢。
第2个回答  2012-12-27
String dir= f.getAbsolutePath();
dir= dir.substring(0, dir.length()-4)+"_1.txt";
File fn= new File(dir);
try{
FileWriter out= new FileWriter(fn);
for(int p=0;p<text.size();p++){
String s=text.get(p);
out.write(s);
}
out.flush();
}catch(IOException e3){
textArea.append("生成密钥出错:"+e3+'\n');
}finally{
if(out != null){
out.close();
}
}