文件读取和写入 问题
为什么写文件时最后如果不关闭文件流的话将不会写入内容???非常感谢!!!
这是我的源码:若去掉(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()));