Search code examples
javaiobufferedreader

Store specific piece of text from text file into array using bufferedReader


-Java- I have a text file in which I am storing ID number, First Name, and Last Name on each line. I'm using BufferedReader to display the text files line by line. However I then need to take the ID number only from each line and store it into an array. If anyone can help it would be greatly appreciated.


Solution

  • As you said, you are already printing the line read from file, next you just need to split the line with the delimiter you have in file. Assuming you have comma as the delimiter, all you need to do is, split the line with comma and access the first element and store it in the List,

    Here is the sample code,

    public static void main(String[] args) throws Exception {
        try(BufferedReader br = new BufferedReader(new FileReader("filename.txt"))) {
            String line = null;
            List<String> idList = new ArrayList<String>();
    
            while((line = br.readLine()) != null) {
                System.out.println(line); // you already printing it
                String[] tokens = line.split("\\s*,\\s*"); // assuming your line is like this --> 123, Pushpesh, Rajwanshi
                if (tokens.length > 0) {
                    idList.add(tokens[0]); // ID will be accessed at zero index
                }
            }
    
            idList.forEach(System.out::println);
        }
    
    }
    

    Using Java8 and above, you can do it in one liner.

    List<String> idList = Files.lines(Paths.get("filename.txt")).filter(x -> x.trim().length() > 0)
            .map(x -> x.split("\\s*,\\s*")).map(x -> x[0]).collect(Collectors.toList());
    
    idList.forEach(System.out::println);