我正在尝试将 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));
用于这两个的构造函数:
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
这两者都存储在 Vehicle ArrayList 中。保存到文本文件的代码:
private static void saveFile(ArrayList<Vehicle> vehs){
File fileName = new File("VehicleList.txt");
try {
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
for (int i = 0; i < vehs.size(); i++){
output.write(vehs.get(i).toString() + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "I cannot create that file");
}
}
我在 VehicleList.txt 中的输出:
vehicle ID = QJT123 Description = Starlet 99 Status = A Daily Rate = 35.0 Odometer reading = 190000vehicle ID = TUX132 Description = BWM 05 Status = A Daily Rate = 90.0 Odometer reading = 12000 Mileage allowance = 100 service length = 10000 Last Service = 5000
如何在写入新的 ArrayList 对象时添加每个新行,例如:
vehicle ID = QJT123 Description = Starlet 99 Status = A Daily Rate = 35.0 Odometer reading = 190000
vehicle ID = TUX132 Description = BWM 05 Status = A Daily Rate = 90.0 Odometer reading = 12000 Mileage allowance = 100 service length = 10000 Last Service = 5000
我尝试过使用 vehs.get(i).toString() + "\n"
但似乎不起作用。
最佳答案
很可能,您的平台不会将\n 视为换行符 - 这取决于操作系统。
获取正确换行标记的一种方法:
String lineSep = System.getProperty("line.separator");
或者更简单:
String lineSep = System.lineSeparator();
而不是使用+ "\n"
,而是在代码中使用+ lineSep
。
关于java - 从每个 ArrayList 对象具有多个值的 ArrayList 写入文本文件 (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154705/