简体   繁体   中英

Problem with Reading a txt File into an ArrayList

I am writing a code to read some text from the txt file which looks like this:

Car:
     Model: Ford
     Color: Red
     Cost: $123123.91
     Car Type: Sedan
     Towing: Included

Car:
     Model: Mitsubishi
     Color: Yellow
     Cost: $12312.00
     Car Type: Sedan
     Towing: Not Included

Car:
     Model: Honda
     Color: Grey
     Cost: $1231.00
     Car Type: Sedan
     Towing: Not Included

to an Arraylist. but the all the text gets stored at index position 0.

I want each order to be stored in a different index position.

The Arraylist 'orders' stores orders entered into gui which works perfectly. These orders are written to a text file when exit is pressed

On the next run when i press load button all the orders are read from the same text file to a different ArrayList 'orders2'.

I have tried using the for loop but the problem seems to be with the way i read/store orders to the text file.

public void save() throws FileNotFoundException {

    PrintWriter pw = new PrintWriter(new FileOutputStream(fileName, false));

    for (Object orderlist : orders) {
        pw.println(orderlist);
    }
    pw.close();
}

public void load() throws FileNotFoundException {

    FileInputStream fileIn = new FileInputStream(fileName);
    Scanner scan = new Scanner(fileIn);
    scan.useDelimiter("  ");
    while (scan.hasNext()) {

        orders2.add(scan.next());
    }

    System.out.println(orders2.get(0));
}

public void actionPerformed(ActionEvent e) {

    if (e.getActionCommand().equals("Exit")) {
        try {
            save();
        } catch (FileNotFoundException f) {
            f.printStackTrace();
        }

        System.exit(0);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
}

scanners work by tokenizing the stream you give it as input. Tokens are things that are separated by a separator. You told it that tokens are separated by two spaces. Given that your text file doesn't contain 2 spaces anywhere inside it, the whole content, soup to nuts, is one single token.

If I read your code (which is incomplete), I see for (Object orderlist: orders) : This can't be right; that implies that orders is a list or array of lists of orders. You really have a list of list of orders? Neither an array nor a list would print like that, so I doubt it; that means your variable names are misleading, likely because you're not quite aware of what your own code is doing. Furthermore, Using Object there is likely not correct. Surely orders is an array or list of Order objects or perhaps String objects.

With that more clear this code would be easier to understand and comment on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM