0

如何编写与 存在的文件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();
    }
 }
4

5 回答 5

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

如果你想追加到文件

于 2012-11-05T13:01:48.227 回答
1

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

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 
于 2012-11-05T13:01:05.140 回答
1

如果您打算编写纯文本,请尝试使用 aFileWriter而不是。FileOutputStream

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

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

于 2012-11-05T13:01:59.663 回答
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();
    }
 }
于 2012-11-05T13:00:44.683 回答
0

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

FileOutputStream d = new FileOutputStream(file, append);
于 2012-11-05T13:02:43.623 回答