从ArrayList写入文本文件,每个ArrayList对象具有多个值(java)

时间:2017-05-24 09:43:05

标签: java arraylist text-files bufferedreader filewriter

我正在尝试将我的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",但似乎无效。

2 个答案:

答案 0 :(得分:2)

最有可能的是,您的平台没有看到\ n作为换行符 - 该东西取决于操作系统。

获取正确换行标记的一种方法:

String lineSep = System.getProperty("line.separator");

甚至更简单:

String lineSep = System.lineSeparator();

而不是使用+ "\n",而是在代码中执行+ lineSep

答案 1 :(得分:1)

BufferedWriternewLine()方法,如果您将output声明为BufferedWriter,则可以使用该方法。

private 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");
    }
}

对于方法的javadoc:

  

写一个行分隔符。行分隔符字符串由。定义   系统属性line.separator,并不一定是单一的   换行符('\ n')字符。