Home > OS >  How to read a text file and add lines of it into an array in Java?
How to read a text file and add lines of it into an array in Java?

Time:12-01

I am new to coding and I was wondering how I would be able to add the lines of my text file into an array in my program. My code looks like this:

import java.io.*;
public class Test {
    
    static String [] name = new String [3];
    static String [] surname = new String [3];
    
    public static void main(String[] args) {
        try{
            BufferedReader reader =null;
            String currentLine = reader.readLine();
            reader=new BufferedReader(new FileReader("Names.txt"));

            int x=0;
            
            while(currentLine!=null){
                name[x]=reader.readLine();
                currentLine=reader.readLine();
                surname[x]=reader.readLine();
                currentLine=reader.readLine();
                x=x 1;
            }
        }
        catch(Exception e){
            System.out.println("The following error occured:"   e.getMessage());
        }
        
        for(int x =0; x<name.length; x  ){
            System.out.println(
            "name:"   name[x]   "\n" 
            "surname: "   surname[x]  "\n"
            );
        }
    }

The error I am getting is Cannot invoke "java.io.BufferedReader.readLine()" because "reader" is null. How do I fix that?

CodePudding user response:

  • BufferedReader object is null and you are trying to access which is not possible in java.
  • I didn`t get what exactly you try to do but you can do something like this.
public class Task3 {

    static String [] name = new String [3];
    static String [] surname = new String [3];
    
    public static void main(String[] args) {
        try{
            BufferedReader reader =null;
            reader=new BufferedReader(new FileReader("/home/ancubate/names.txt"));
            List<String> lines = reader.lines().collect(Collectors.toList());
            int x=0;
            
            while(lines.size() != (x 1)){
                name[x]=lines.get(x);
                surname[x]=lines.get(x);
                x=x 1;
                
            }
        }
        catch(Exception e){
            System.out.println("The following error occured:"   e.getMessage());
        }
        
        for(int x =0; x<name.length; x  ){
            System.out.println(
            "name:"   name[x]   "\n" 
            "surname: "   surname[x]  "\n"
            );
        }
    }

}

  • reader.lines() - to get all the lines from the file
  • collect(Collectors.toList()) - stream API collect as list

CodePudding user response:

I am not sure of my answer. I think it is because you forgot to import java io package into the program. Hope you got it.

  • Related