简体   繁体   English

如何将 txt 文件添加到 Arraylist (Java)

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

I have a file called Vehicle.txt contains example:我有一个名为 Vehicle.txt 的文件包含示例:

(123,123,123,123,123 (123,123,123,123,123
456,4,456,456,456) 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.我建议使用 FileReader 和 BufferedReader,而不是使用 Scanner。 A BufferedReader has a method called readLine() that reads the next line. BufferedReader 有一个名为 readLine() 的方法,用于读取下一行。

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您可以使用 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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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