简体   繁体   中英

How can I add the txt file into an Arraylist (JaVa)

I have a file called Vehicle.txt contains example:

(123,123,123,123,123
456,4,456,456,456)

The output only executed the first line will be add into the arraylist. I just wonder how can I read for the second line.

    static void readVehicleFile() {
        Vehicle vehicle;
        try {

            input = new Scanner(new File("Vehicle.txt"));
            StringTokenizer tokenizer =  new StringTokenizer(input.next(),",");
            while (input.hasNextLine() && tokenizer.hasMoreTokens()) {
                vehicle = new Vehicle();
                vehicle.setPlateNumber(tokenizer.nextToken());
                vehicle.setNumOfYear(Integer.parseInt(tokenizer.nextToken()));
                vehicle.setMake(tokenizer.nextToken());
                vehicle.setModel(tokenizer.nextToken());
                vehicle.setEngineCapacity(Integer.parseInt(tokenizer.nextToken()));
                vehicle.setOwnerID(Integer.parseInt(tokenizer.nextToken()));


                vehicleList.add(vehicle);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

Instead of using Scanner, I recommend using FileReader and a BufferedReader. A BufferedReader has a method called readLine() that reads the next line.

private static String[] getCSV(File path) {
        if (!path.exists())
            return null;
        try {
            ArrayList<String> array = new ArrayList<>();
            FileReader reader= new FileReader(path);
            BufferedReader br = new BufferedReader(reader);
            String line;
            while((line = br.readLine()) != null){
                String[] csv = line.split(",");
                array.addAll(Arrays.asList(csv));
            }
            br.close();
            reader.close();
            return Arrays.copyOf(array.toArray(), array.size(), String[].class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

This is a method I made a while ago that returns an array of String with the comma separated values of your file. You can add a tiny modification to remove the parenthesis from the first and last values. Then, you can just use the values in that String array to set your vehicle methods.

The Exception handling should be a bit more polished, if there's an error reading the file the readers will not close, resulting in a memory leak. I hope this at least helps you read your values.

Note: If you want a walkthrough of the method, add a comment and I'll explain further.

You can use java.nio.file.Files.readline

import java.nio.file.Files;
import java.nio.file.Paths;    
...
List<String> lines = Files.readAllLines(Paths.get("/tmp/readlines.txt"));

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