写一个已经存在的文件

时间:2012-11-05 12:56:05

标签: java file

如何编写FileOutputStream存在的文件?当我运行两次此程序时,第二次oosfos为空

 public class ReadFile {
    static FileOutputStream fos = null;
    static ObjectOutputStream oos = null;
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        File f = new File("file.tmp");
        if (f.exists()) {
            //How to retreive an old oos to can write on old file ?
            oos.writeObject("12345");
            oos.writeObject("Today");
        }
        else
        {
            fos = new FileOutputStream("file.tmp");
            oos = new ObjectOutputStream(fos);
        }
        oos.close();
    }
 }

5 个答案:

答案 0 :(得分:2)

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f,true));

如果你想附加到文件

答案 1 :(得分:1)

如果您不想覆盖该文件,请将true参数添加到File或Fileoutputstream构造函数

new FileOutputStream( new File("Filename.txt"), true );

Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning 

答案 2 :(得分:1)

如果您打算撰写纯文本,请尝试使用FileWriter代替FileOutputStream

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
    out.println("the text");

第二个参数(true)将告诉追加文件。

答案 3 :(得分:0)

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f, true));

在您的代码中,您有ObjectOutputStream oos = null;,因此oosnull。你需要初始化它。像这样:

public class ReadFile {
    static FileOutputStream fos = null;
    static ObjectOutputStream oos = null;
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        File f = new File("file.tmp");
        oos = new ObjectOutputStream(new FileOutputStream(f, true));
        if (f.exists()) {
            //How to retreive an old oos to can write on old file ?
            oos.writeObject("12345");
            oos.writeObject("Today");
        }
        else
        {
            fos = new FileOutputStream(f, true);
            oos = new ObjectOutputStream(fos);
        }
        oos.close();
    }
 }

答案 4 :(得分:0)

只需创建新的FileOutputStream,将第二个参数设置为true

FileOutputStream d = new FileOutputStream(file, append);
相关问题