为什么写文件时最后如果不关闭文件流的话将不会写入内容???非常感谢!!!这是我的源码:若去掉(bw.close();和fw.close();语句将不能写入内容)package com.inspur;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;/**
 * 
 * 作者: 柯连德 日期: 2007-8-31 版本: 0.1 文件名:UpdateFileForBufferChar.java
 */
public class UpdateFileForBufferChar { /**
 * 功能:
 * 
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
String fname = "source.txt";
String child = "copy";
new UpdateFileForBufferChar().update(fname, child);
} private void update(String fname, String child) throws IOException { File f1 = new File(fname);
File childdir = new File(child);
if (f1.exists()) {
if (!childdir.exists()) {
System.out.println(childdir.getName() + " was created!");
childdir.mkdir();
}
File f2 = new File(childdir, fname);
if (!f2.exists() || f2.exists()
&& f1.lastModified() > f2.lastModified()) {
copy(f1, f2);
}
if (f2.length() == 0) {
System.out.println("f2 is empty");
} else {
getinfo(f1);
getinfo(childdir);
} } else {
System.out.println(f1.getName() + " is not found!");
}
} private static void copy(File f1, File f2) throws IOException {// if (!f2.exists()) {
// f2.createNewFile();
// }
FileWriter fw = new FileWriter(f2);
BufferedReader br = new BufferedReader(new FileReader(f1));
BufferedWriter bw = new BufferedWriter(fw);
String text;
text = br.readLine();
while (text != null) {
bw.write(text+"\r\n");
System.out.println(text);
text = br.readLine(); }
br.close();
bw.close();
fw.close();
} private void getinfo(File f) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:mm");
if (f.isDirectory()) {
System.out.println("<Dir>: " + f.getAbsolutePath());
File[] flist = f.listFiles();
for (int i = 0; i < flist.length; i++) {
getinfo(flist[i]);
}
} else {
System.out.println("<File>: " + f.getAbsolutePath() + "\t"
+ f.length() + "\t" + sdf.format(f.lastModified())); }
}}

解决方案 »

  1.   

    close方法会自动flush
    也就是说,你上面的代码使用了缓冲区,那么,在缓冲区没有填满的情况下,要使用flash方法,把缓冲区的内容刷出去。尤其是输出缓冲区,在每一次传输的最后,一般都要使用flash方法将缓冲区中剩余的内容刷出去。这样,就确保的数据的一致性,否则,会有 部分数据仍然停留在缓冲区当中的情况。
    你不妨把source.txt文件的内容写得多一些,然后不使用bw.close();和fw.close();两个方法。这样,应该会有部分内容被复制到copy文件中去。
    然后,添加bw.flush()和fw.flush()方法试一试,应该就会有全部数据了。
    当然close方法,按正规方法也是要写到程序中的。
    还有,不好意思,你的代码还有个小毛病。正规编程,应该  是  File类的对应的对象要在使用后调用close方法,将文件关闭。这样,其他的应用程序,在该程序未退出的时候就可以操作该程序所关闭的File对象了。
      

  2.   

    应该  是  File类的对应的对象要在使用后调用close方法,将文件关闭。这样,其他的应用程序,在该程序未退出的时候就可以操作该程序所关闭的File对象了。
    什么意思,能解释一下吗?谢谢!!