Search code examples
javabufferedreader

Reading a .txt file using BufferedReader and FileReader


I used BufferedReader and FileReader to read a file but everytime I read it, it just displays no name found. Thanks in advance.

BufferedReader ifile = new BufferedReader (new FileReader ("data.txt"));
    String N;
    while(true)
    {
        N=ifile.readLine();
        if (N == null){
            System.out.print("\fNo name found\n");
            break;
        }
        number = Integer.parseInt(ifile.readLine());
        house = ifile.readLine();
        form = ifile.readLine();
        dob = ifile.readLine();
        System.out.println("Name: " + N + "\nNumber: " + number + "\nHouse: " + house + "\nForm: " + form + "\nDate of Birth: " + dob);
    }
    ifile.close();

Solution

  • Answer might have already been given in another topic like: Read all lines with BufferedReader

    So it might be a duplicate.

    However when you read a file via BufferedReader it is recommended you do it like

            FileReader filereader = new FileReader("data.txt");
            BufferedReader ifile = new BufferedReader(filereader); 
            String N;
            ArrayList<String> file_contents= new ArrayList<String>();
            //List will now contain the whole txt
    
            try {
                while((N = input.readLine()) != null) {
                    file_contents.add(N);
                }
                ifile.close();
            }
            catch(IOException e){
                e.printStackTrace();
            }
    

    And then break the list's contents to get what you want.

    Using a try/catch block can avoid the error of not knowing how to handle that the file "data.txt" cannot be read.

    Your way of doing it (while(true)) doesn't pass the name in any variable so it can be printed out and also just checks if the 1st line of your data.txt file is empty or not and does nothing with the remaining lines if that condition is true.

    In addition to the above check if the source of your problem is in the txt file. For example if its structure is the way you want it to be.