簡體   English   中英

寫一個已經存在的文件

[英]Write a file that already exists

如何編寫FileOutputStream存在的文件? 當我運行兩次此程序時,第二次oosfos為null

 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();
    }
 }
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f,true));

如果要附加到文件

如果您不想覆蓋文件,則將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 

如果打算編寫純文本,請嘗試使用FileWriter而不是FileOutputStream

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

第二個參數( true )告訴追加到文件。

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();
    }
 }

只需創建新的FileOutputStream並將第二個參數設置為true

FileOutputStream d = new FileOutputStream(file, append);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM