Search code examples
javaarraylisttext-filesbufferedreaderfilewriter

Writing into text file from ArrayList that has multiple values per ArrayList object (java)


I am trying to save my ArrayList into a text file. But the format of how it is saved is wrong. My code:

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));

Constructor used for these 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

Both of these are stored into the Vehicle ArrayList. Code to save to text file:

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

My output in 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

How do i make it such that each new line is added when writing in a new ArrayList object, e.g:

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

I've tried using vehs.get(i).toString() + "\n" but it doesn't seem to work.


Solution

  • BufferedWriter has a newLine() method, you may use that if you declare output as a 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");
        }
    }
    

    Also for the javadoc of the method :

    Writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.