怎样将 txt 文件添加到 ArrayList 中(Java)

huangapple go评论69阅读模式
英文:

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

问题

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

}

英文:

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

答案1

得分: 1

替代使用Scanner,我建议使用FileReader和BufferedReader。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 array.toArray(new String[array.size()]);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

这是我一段时间前写的一个方法,它返回一个包含文件中逗号分隔值的字符串数组。你可以稍作修改,去掉第一个和最后一个值的括号。然后,你可以使用该字符串数组中的值来设置你的车辆方法。

异常处理应该更加完善,如果在读取文件时出现错误,读取器将不会关闭,导致内存泄漏。我希望这至少能帮助你读取你的值。

注意:如果你想要这个方法的详细步骤说明,请添加一条评论,我会进一步解释。

英文:

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&lt;String&gt; array = new ArrayList&lt;&gt;();
			FileReader reader= new FileReader(path);
			BufferedReader br = new BufferedReader(reader);
			String line;
            while((line = br.readLine()) != null){
			    String[] csv = line.split(&quot;,&quot;);
                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.

答案2

得分: 0

可以使用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"));
英文:

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

import java.nio.file.Files;
import java.nio.file.Paths;    
...
List&lt;String&gt; lines = Files.readAllLines(Paths.get(&quot;/tmp/readlines.txt&quot;));

huangapple
  • 本文由 发表于 2020年9月23日 20:57:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64028500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定