我需要在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());
「在文件的結尾java寫的」別告訴我你已經GOOGLE了,我不會相信你的。 – Julien
http://stackoverflow.com/questions/8544771/how-to-write-data-with-fileoutputstream-without-losing-old-data – TheStackHasGrownIntoTheHeap
我已經嘗試寫在文件的末尾,但然後沒有閱讀正確的字符串。我從java開始,對不起,如果你是一件容易的事情。我不明白爲什麼要投票,如果這是一個人們詢問他的疑惑並學習的地方 – masmic