我从java开始,现在正在做一些读/写文件的练习。
我用这种格式编写字符串:
String wordList: word1 word2 word3; word4 word5 word6; code
然后我使用以下代码将其写入文件:
public void writeSelling(String wordList) throws IOException {
fileOutPutStream = new FileOutputStream (file);
write= new ObjectOutputStream (fileOutPutStream);
write.writeObject(wordList);
write.close();
contador++;
}
但是我无法正确执行的地方是阅读它时。目前,我在读取文件内容时得到的是 null,所以我认为我在方法上做错了什么。
这是我用来读取文件的方法:
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;
}
我在主文件上这样调用这个方法:
public static void listSelling(){
ArrayList objects;
try{
objects = sellingObject.readSelling();
for (Iterator it = sellingObject.iterator(); it.hasNext();) {
String s = (String)it.next();
System.out.println(s.toString());
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
我没有足够的知识来使用迭代器,所以也许我没有正确使用它。
更新——“file.dat”的定义
该文件在其他类中是这样定义的:
private final String file;
public WriteReadObject(String file){
this.file= file;
}
然后在主文件中这样调用:
static WriteReadObject selling= new WriteReadObject("file.dat");
更新 2 --
我发现当我写入文件时,我正在写入一个空值,这就是它失败的地方。
我有这个:
字符串一 = word1 word2 word3
字符串二 = word4 word5 word6
在调用 write 方法写入文件之前,我将这 2 个字符串添加到另一个字符串中以仅获取一个字符串。为此,我创建了这个方法:
public String add(String c, String m){
sellinglist[contador] = c + m;
contador++;
String list= sellinglist[contador];
return list;
}
其中 c 是字符串一,m y 是字符串二
最佳答案
alexey28 说得对 - 你正在重写文件,最后只有最后一个插入。无论如何,仅仅改变 FileOutputStream
参数来使其工作并不是那么简单 - 你不能仅仅附加到 ObjectOuputStream
- 如果你愿意,请参阅 here 。它会破坏流,从而导致 StreamCorruptedException。
最好的解决方案是在开始时打开ObjectOutputStream
一次,写入所需的所有对象,然后关闭流。
这完全取决于您如何接收要写入的数据(如果您正在编写字符串,那么不以二进制模式执行可能会更舒服,但文本 - here 是解释如何执行此操作的教程)。
如果您想要代码如何简单地编写字符串列表,那么您可以尝试以下操作:
/* writing */
public void writeSelling(List<String> wordLists) throws IOException {
fileOutPutStream = new FileOutputStream (file);
write= new ObjectOutputStream (fileOutPutStream);
for (String s : wordLists) {
write.writeObject(s);
}
write.close();
contador++;
}
现在您可以在调用 writeSelling()
的位置更改代码。
/* calling method */
List<String> wordLists = new ArrayList<String>();
{ // it's probably loop
String wordList = // somehow receive list like word1 word2 word3; word4 word5 word6; code
wordLists.add(wordList);
}
writeSelling(wordLists);
其余部分保持不变。不要多次调用 writeSelling()
方法,仅调用一次。
关于java - 在java上读取.dat文件获取null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20242315/