【发布时间】:2013-12-14 05:55:36
【问题描述】:
我需要在 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());
【问题讨论】:
-
别告诉我你在 google 上搜索过“java write at the end of a file”,我不会相信你。
-
我尝试在文件末尾写入,但没有正确读取字符串。我从java开始,对不起,如果对你来说是一件容易的事。我不明白为什么要投反对票,如果这应该是人们提出疑问和学习的地方
标签: java string serialization fileinputstream fileoutputstream