因此,我试图编写和读取数据文件,并声明一个新类型' GroceryStore'我读完数据文件后。我在运行程序时遇到异常错误。有人可以向我解释为什么会发生这种情况以及如何解决这个问题?感谢。
这是我的写数据文件方法:
{
FileOutputStream file = null;
ObjectOutputStream outStream = null;
file = new FileOutputStream(new File(filename));
outStream = new ObjectOutputStream(file);
outStream.writeObject(store1);
System.out.print(filename + " was written\n");
}
这是我的读数据文件方法
{
FileInputStream file = null;
ObjectInputStream inStream = null;
file = new FileInputStream(new File(filename));
inStream = new ObjectInputStream(file);
GroceryStore newStore = (GroceryStore) inStream.readObject();
store1 = newStore;
System.out.print(filename + " was read\n");
}
答案 0 :(得分:0)
乍一看,用于阅读的代码似乎想要快速将它放到GroseryStore类中,可能需要进行一些解析才能获得它。尝试System.out.println读取器的输入,然后你知道你有什么,然后解析/切碎并切成你需要/想要的东西。
因此,第二个为读/写操作创建一个类。作为写入如何适用于简单文本输出文件的示例,您可以使用以下内容:
private String file_name = "FileName";
private String file_extention = ".txt";
BufferedWriter writer = null;
public void writeTextToFile(String stuff_to_file) {
// trying to write (and read) is a bit hazardous. So, try, catch and finally
try {
File file = new File(file_name + file_extention);
FileOutputStream mFileOutputStream = new FileOutputStream(file);
OutputStreamWriter mOutputStreamWriter = new OutputStreamWriter(mFileOutputStream);
writer = new BufferedWriter(mOutputStreamWriter);
writer.write(stuff_to_file); // and finally we do write to file
// This will output the full path where the file will be written to.
System.out.println("\nFile made, can be found at: " + file.getCanonicalPath());
} catch (Exception e) { // if something went wrong we like to know it.
e.printStackTrace();
System.out.println("Problem with file writing: " + e);
} finally {
try { // Close the writer regardless of what happens...
writer.close();
} catch (Exception e) { // yes, even this can go wrong
e.printStackTrace();
} // close try / catch
} // close finally
} // close method