2013-11-28 79 views
1

我需要在eclipse上的文件上寫字符串而不覆蓋舊字符串。該函數可能是這樣的:創建一個字符串,將其保存在文件中,創建另一個字符串,將其保存在文件中,這與幾個字符串。使用ObjectOutputStream寫入文件而不覆蓋舊數據

字串必須在下格式:

String one = name surname surname; value1 value2 value3; code 

所以該方法是:創建的字符串,將它保存在該文件。創建另一個字符串,將其保存在文件上等。 然後,在將想要的字符串保存到文件後,我需要讀取列出控制檯上所有字符串的文件。

但是現在,我只能在文件上保存一個字符串,然後列出它。如果我保存兩個字符串,第二個會覆蓋第一個字符串,而且不管它是否正確,因爲當我想列出它們時,會返回空值。

這是在文件寫入字符串的方法:

public void writeSelling(List<String> wordList) throws IOException { 
    fileOutPutStream = new FileOutputStream (file); 
    write= new ObjectOutputStream (fileOutPutStream); 
    for (String s : wordList){ 
     write.writeObject(s); 
    } 
    write.close(); 
} 

這是怎麼我的主類調用write方法:

List<String> objectlist= new ArrayList<String>(); 
    objectlist.add(product); //Product is the string I save each time 
          //which has the format I commented above 
    writeSelling(objectlist); 

這是方法, 從文件中讀取字符串

public ArrayList<Object> readSelling() throws Exception, FileNotFoundException, IOException { 
    ArrayList<Object> objectlist= new ArrayList<Object>(); 
    fileInPutStream = new FileInputStream (file); 
    read= new ObjectInputStream (fileInPutStream); 
    for (int i=0; i<contador; i++){ 
     objectlist.add(read.readObject()); 
    } 
    read.close(); 
    return objectlist; 
} 

而且我這是怎麼通話讀取主類

ArrayList sellingobjects; 
sellingobjects= readSelling(); 
for (Iterator it = sellingobjects.iterator(); it.hasNext();) { 
     String s = (String)it.next(); 
} 
System.out.println(s.toString()); 
+1

「在文件的結尾java寫的」別告訴我你已經GOOGLE了,我不會相信你的。 – Julien

+0

http://stackoverflow.com/questions/8544771/how-to-write-data-with-fileoutputstream-without-losing-old-data – TheStackHasGrownIntoTheHeap

+0

我已經嘗試寫在文件的末尾,但然後沒有閱讀正確的字符串。我從java開始,對不起,如果你是一件容易的事情。我不明白爲什麼要投票,如果這是一個人們詢問他的疑惑並學習的地方 – masmic

回答

2

您應該打開這樣的文件,該文件

new FileOutputStream(file, true) 

在追加的字符串創建文件輸出流寫入由 指定的File對象表示的文件。如果第二個參數爲true,則字節將 寫入文件的末尾而不是開頭。將創建一個新的 FileDescriptor對象來表示此文件連接。

但是Java序列化不支持「追加」。您不能將ObjectOutputStream寫入文件,然後以追加模式再次打開該文件,並向其寫入另一個ObjectOutputStream。你必須每次重寫整個文件。 (即,如果要將對象添加到文件中,則需要讀取所有現有對象,然後再次使用所有舊對象和新對象編寫該文件)。

我會sugest你使用DataOutputStream

public void writeSelling(List<String> wordList) throws IOException { 
    fileOutPutStream = new FileOutputStream (file,true); 
    DataOutputStream write =new DataOutputStream(fileOutPutStream); 
    for (String s : wordList){ 
     d.writeUTF(s); 
    } 
    write.close(); 
} 
+0

我已經嘗試過,但沒有閱讀我寫的新字符串,讀取之前存在的字符串。我必須對'new FileInputStream(file,true)'做同樣的事情嗎? – masmic

+0

@ masmic_87不,你不能這樣做。 –

+0

好吧,即使我把'true'放在那裏,如果我寫一個字符串,就不會正確寫入/讀取,而是讀取我之前擁有的字符串,而不是新字符串。如果我寫第二個,拋出這個:'錯誤閱讀文件無效的類型代碼:AC' – masmic

相關問題