日期:2014-05-20  浏览次数:20949 次

FileOutputStream自动覆盖文件的问题
下面这段代码不会输出任何数据,因为在bufferedReader读取文本信息前
FileOutputStream已经将D:\Debug.log覆盖为空文件..根本没有调用write方法..
删除FileOutputStream后就能正常的读取...这是为什么呢
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.swing.JOptionPane;

public class _Writer
{
/**
 * @param args
 */
public static void main(String[] args)
{
File hosts = new File("D:\\Debug.log");
FileOutputStream os = null;
FileInputStream is = null;
BufferedReader br = null;
BufferedWriter bw = null;
try
{
is = new FileInputStream(hosts);
os = new FileOutputStream(hosts);
br = new BufferedReader(new InputStreamReader(is));
bw = new BufferedWriter(new OutputStreamWriter(os));
String str = null;
while ((str = br.readLine()) != null)
{
System.out.println(str);
}
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "hosts文件不存在!");
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "IO异常!");
} finally
{
try
{
if (os != null)
os.close();
if (is != null)
is.close();
if (br != null)
br.close();
if (bw != null)
bw.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "CLOSE异常!");
}
}
}
}
java io fileoutputstream 奇葩

------解决方案--------------------
你这是想干嘛啊?干嘛又读又写,还是同一个文件。你的目的是什么?
------解决方案--------------------
new FileOutputStream(hosts); 改成 new FileOutputStream(hosts , true); 表示追加文件
------解决方案--------------------
就如楼上说的,
 os = new FileOutputStream(hosts);改成
 os = new FileOutputStream(hosts,true);就好了
至于原因,看源码


  public FileOutputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null, false);
    }

继续追踪

 public FileOutputStream(File file, boolean append)
        throws FileNotFoundException
    {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(name);
        }
        if (name == null) {
            throw new NullPointerException();
        }
        this.fd = new FileDescriptor();
        this.append = append;

        fd.incrementAndGetUseCount();
        open(name, append);
    }

找到open方法

 /**
     * Opens a file, with the specified name, for overwriting or appending.
     * @param name name of file to be opened
     * @param append whether the file is to be opened in append mode
     */
    private native void open(String name, boolean append)
        throws FileNotFoundException;