2012-11-05 54 views
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(); 
    } 
} 

回答

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

如果要追加到文件

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

如果你不想overrite文件,真正的參數添加到文件或文件的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 
0

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

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

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

0

只是設置爲true

FileOutputStream d = new FileOutputStream(file, append); 
第二個參數創建新 FileOutputStream
相關問題