<分区>
我需要在 eclipse 上的文件上写入字符串而不覆盖旧字符串。该函数类似于:创建一个字符串,将其保存在文件中,创建另一个字符串,将其保存在文件中,这包含多个字符串。
字符串具有以下格式:
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;
}
这就是我在主类上调用read的方式:
ArrayList sellingobjects;
sellingobjects= readSelling();
for (Iterator it = sellingobjects.iterator(); it.hasNext();) {
String s = (String)it.next();
}
System.out.println(s.toString());