【发布时间】:2013-11-27 12:18:13
【问题描述】:
我是从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++;
}
但我不能正确地做到这一点是在阅读时。目前,我在读取文件内容时得到的是空值,所以我认为我在方法上做错了。
这是我用来读取文件的方法:
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 方法写入文件之前,我将这两个字符串添加到另一个字符串中以仅获取一个字符串。为此,我创建了这个方法:
public String add(String c, String m){
sellinglist[contador] = c + m;
contador++;
String list= sellinglist[contador];
return list;
}
其中 c 是字符串 1,m y 是字符串 2
【问题讨论】:
-
我认为我们遗漏了一些关键细节,无法在这里为您提供帮助。
file变量的声明在哪里,是否曾为其赋值? -
打开你的文件,检查数据是否已经被你的代码写入文件中。
-
@nineside 我已经用文件定义更新了帖子
-
@masmic_87 交换行
contador++;和String list= sellinglist[contador]; -
@masmic_87 改变位置,让它:
sellinglist[contador] = c + m; String list= sellinglist[contador]; contador++; return list;