繁体   English   中英

将txt文件的不同行读入不同的ArrayList

[英]Reading different lines of a txt file into different ArrayList

我有一个文件,其中有两行包含整数输入。 我想将整数的第一行读入Arraylist<Integer> ,并将输入的第二行读入其他Arraylist 我如何修改以下代码以有效地做到这一点。 我无法理解如何使用定界符。

import java.util.*;
import java.io.*;
public class arr1list {
    public static void main(String[] args) throws FileNotFoundException {
        ArrayList<Integer> list1=new ArrayList<Integer>();
        File file=new File("raw.txt");
        Scanner in=new Scanner(file);
        Scanner.useDelimiter("\\D"); //the delimiter is not working.

        while(in.hasNext())
            list1.add(in.nextInt());
        System.out.println(list1);
        in.close();
    }
}

除了上面的答案外,使用Java 8样式

    BufferedReader reader = Files.newBufferedReader(Paths.get("raw.txt"), StandardCharsets.UTF_8);
    List<List<Integer>> output = reader
        .lines()
        .map(line -> Arrays.asList(line.split(" ")))
        .map(list -> list.stream().mapToInt(Integer::parseInt).boxed().collect(Collectors.toList()))
        .collect(Collectors.toList());

结果,您将获得整数列表列表,例如[[1、2、3、4、5],[6、7、8、9、6]]

你能做这样简单的事情吗:

    try (BufferedReader reader = 
            new BufferedReader(new FileReader("path"));) {

        List<Integer> first = new ArrayList<>();

        for (String number: reader.readLine().split(" ")) {

            numbers.add(Integer.parseInt(number));
        }

        // do stuff with first and second

    } catch (IOException ignorable) {ignorable.printStackTrace();}
}

BufferedReader.readLine()将为您处理文件定界符解析。

您可以提取需要一行的方法并将其解析以创建整数List 然后,像上面那样使用reader.readLine()两次读取一行,并调用该方法为每一行生成List即可。

我会做这样的事情:

//Arrays are enough because int is a primitive
int list1[], list2[];

try {
    Scanner in = new Scanner(new FileReader("file.txt"));

    String line1 = (in.hasNextLine()) ? in.nextLine() : "";
    String line2 = (in.hasNextLine()) ? in.nextLine() : "";

    String[] line1_values = line1.split(" "); // Split on whitespace
    String[] line2_values = line2.split(" ");

    int line1Values[] = new int[line1_values.length], line2Values[] = new int[line2_values.length];

    // Map the values to integers
    for(int i = 0; i < line1_values.length; i++)
        line1Values[i] = Integer.parseInt(line1_values[i]);

    for(int i = 0; i < line2_values.length; i++)
        line2Values[i] = Integer.parseInt(line2_values[i]);

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

我对此进行了测试,它适用于文本文件,其值由空格分隔。

暂无
暂无

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

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