我正在尝试将我的Arraylist写入文本文件并将该文件读回到我的ArrayList中。
我使用:
写出了ArrayListprivate static void saveFile(ArrayList<Vehicle> vehs){
File fileName = new File("VehicleList.txt");
try {
FileWriter fw = new FileWriter(fileName);
BufferedWriter output = new BufferedWriter(fw);
for (int i = 0; i < vehs.size(); i++){
output.write(vehs.get(i).toString());
output.newLine();
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "I cannot create that file");
}
}
但是我在阅读文件时遇到了麻烦,无法填写ArrayList。
这是我用来回读ArrayList的代码:
private static void readVFile(ArrayList<Vehicle> vehs) throws FileNotFoundException, IOException{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("VehicleList.txt"));
try {
Object obj = null;
while ((obj = ois.readObject()) != null) {
if (obj instanceof Vehicle) {
Vehicle v = (Vehicle) obj;
vehs.add(v);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
ois.close();
}
}
这个ArrayList需要添加2个构造函数。
构造函数:
public PremiumVehicle(String vehicleID, String description, double dailyRate, int odometer, int allowance, int serLength, int lastOdo) //subclass
public Vehicle(String vehicleID, String description, double dailyRate, int odometer) //Superclass
添加到ArrayList示例:
ArrayList<Vehicle> vehs = new ArrayList<Vehicle>();
vehs.add(new Vehicle("QJT123", "Starlet 99", 35.0, 190000));
vehs.add(new PremiumVehicle("TUX132", "BWM 05 ", 90.0, 12000, 100, 10000, 5000));
当我尝试回读文件时,它会返回给我&#34; StreamCorruptedException:无效的流标题:76656879&#34;。我如何读回我刚刚写入ArrayList的文本文件?提前感谢您的帮助。
修改
我已尝试使用FileOutputStream
和ObjectOutputStream
,但现在它没有记录它的内容。
编辑序列化代码:
private static void saveFile(ArrayList<Vehicle> vehs){
File fileName = new File("VehicleList.txt");
try {
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for (int i = 0; i < vehs.size(); i++){
oos.writeObject(vehs.get(i));
}
oos.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "I cannot create that file");
}
}