尝试将对象写入数组,然后保存到output.data,然后再次读取对象。
写作:
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {
File outFile;
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
outFile = new File("output.data");
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(arr);
JOptionPane.showMessageDialog(null, "File Written Successfully");
oStream.close();
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
读:
private void readBtnActionPerformed(java.awt.event.ActionEvent evt) {
File inFile;
FileInputStream fStream;
ObjectInputStream oStream;
try {
inFile = new File("output.data");
fStream = new FileInputStream(inFile);
oStream = new ObjectInputStream(fStream);
//create an array of assessments
ArrayList <Assessment> xList;
xList = (ArrayList<Assessment>)oStream.readObject();
for (Assessment x:xList) {
JOptionPane.showMessageDialog(null, "Name: " + x.getName() + "Type: " + x.getType() + "Weighting: " + x.getWeighting());
}
oStream.close();
} catch (IOException e) {
System.out.println("Error: " + e);
} catch (ClassNotFoundException ex) {
System.out.println("Error: " + ex);
}
}
代码压缩得很好,文件本身也可以保存。但是当我尝试读取文件时没有任何反应,NetBeans说
&#34;线程中的异常&#34; AWT-EventQueue-0&#34; java.lang.ClassCastException:[Lnetbeansswingexample.Assessment;无法转换为java.util.ArrayList&#34;
代码麻烦似乎是
xList = (ArrayList<Assessment>)oStream.readObject();
非常感谢任何帮助,谢谢。很抱歉,如果答案显而易见,那么编程就是新手。
答案 0 :(得分:4)
根据您获得的例外情况,看起来oStream.readObject()
会返回Assessment
的数组,而不是List
。您可以将其转换为List
:
List <Assessment> xList;
xList = Arrays.asList((Assessment[])oStream.readObject());
或者如果您必须使用java.util.ArrayList
:
ArrayList<Assessment> xList;
xList = new ArrayList<> (Arrays.asList((Assessment[])oStream.readObject()));