简体   繁体   中英

Reading different lines of a txt file into different ArrayList

I have a file with two different lines containing integer inputs. I want to read the first line of integers into an Arraylist<Integer> and the second line of input into some other Arraylist . How can I modify the following code to do that effectively. I am unable to understand how to use delimiter.

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

In addition to answers above, with java 8 style

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

As result you will have List of Lists of Integer, for example [[1, 2, 3, 4, 5], [6, 7, 8, 9, 6]]

Can you do something simple like this:

    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() will take care of file delimiter parsing for you.

You could extract method which takes one line and parses it to create List of Integers. Then it is a matter of reading line, twice, as above with reader.readLine() and calling the method to generate List for each line.

I would do something like this :

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

I tested this and it works fine for text files which values are separated by white spaces.

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