簡體   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