I have a problem outputting the contents of a text file. Whenever I try to display the contents of a file a "null" word is printed at the end of the output.

Any help would be deeply appreciated.

import java.io.*;
import java.lang.*;

public class prog1
{
	public static void main(String[] args)
	{
		readFile();
	}	//end of main
	
	public static boolean isDoubleString(String s)
    {
       try
       {
			Double.parseDouble(s);
			return true;
		}
		
		catch(NumberFormatException nx)
		{
			return false;
		}
    }   // end of isDoubleString()
	
	public static String kbdInput(String prompt)
	{
		String s = "";
		System.out.print(prompt);
		
		try
		{
			BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
			s = kbd.readLine();
		}
		
		catch(IOException iox)
		{
			System.out.println("No keyboard detected...");
			System.exit(0);
		}
		
		return s;
	}	//end of kbdInput
	
	public static void readFile()
	{
		String fname = kbdInput("Enter file name: ");
		BufferedReader infile = null;
		
		try
		{
			infile = new BufferedReader(new FileReader(fname));
		}
		catch(IOException iox)
		{
			System.out.println("File does not exist...");
			System.exit(0);
		}
		
		String aLine = "";
			
		try
		{
			while(aLine != null)
			{
				aLine = infile.readLine();
				System.out.println(aLine);
			}
			infile.close();
		}
		catch(IOException iox)
		{
			System.out.println("File is empty...");
			System.exit(0);
		}
	} //end of readFile
}

Dani AI

Generated

The stray "null" comes from printing the reader's return value after EOF. In your original loop the code enters the body, calls readLine(), and prints whatever it returns — and at the end readLine() returns null, so "null" gets printed before the loop exits. 's change (moving the read into the loop condition) fixes that by only printing when a real line was returned; and were pointing at the same ordering issue and showed an equivalent pre-read pattern.

A slightly more modern and safer pattern is to let the API give you a stream of non-null lines and rely on try-with-resources so the reader is always closed:

try (BufferedReader br = Files.newBufferedReader(Paths.get(fname), StandardCharsets.UTF_8)) {
    br.lines().forEach(System.out::println);
}

This avoids manual null checks, handles closing for you, and preserves large-file laziness (unlike readAllLines).

A few practical notes you won't find in the thread: readLine() returns null only at EOF — an empty line in the file yields an empty string (""), not null. Initializing your loop variable to "" (or any non-null) and then testing it before you read will produce the exact behavior you saw. Also prefer reporting or rethrowing an IOException instead of calling System.exit() deep inside a helper so callers can decide how to handle errors.

If the "null" still appears, step through one iteration with a debugger or add a quick print of whether the value is null before printing the line; that will make the control-flow mistake obvious.

Recommended Answers

All 6 Replies

aLine = infile.readLine();
System.out.println(aLine);  // Print the last line read, including the null at EOF

how do I fix this problem?
I just started learning java and do not have any experience in it.

This seemed to fix the problem

while((aLine = infile.readLine()) != null)
			{
				System.out.println(aLine);
			}

but I do not know why

To see what is happening, you need to play computer. Step thru the code statements one at a time, keeping track of the values of the variables as you go.

while((aLine = infile.readLine()) != null)

What does this statement do? It will execute the body in {} if ... otherwise it won't

Member Avatar for Member #814414

Remember, order of operations matters. You want to check first, not read in input first.

Sorry forgot to post code.

Actually I find that kind code confusing and I never use it. This is simpler:

// get the first line of the file. If it is not null go in the loop
String aLine = infile.readLine();
while (aLine != null) {

  // the line is not null. So you can do whatever you want to process it
  System.out.println(aLine);

..........

  // at the end of the loop. At the LAST command, read the next line:
  aLine = infile.readLine();
  // if the next line is null, then the loop will exit and you finish reading the file.
  // that is why it must be at the end.
}

At the last command you read the next line, then you go at the top of the loop. If that line is null then there is no line, and you don't continue looping.

Another, more stupid way, is this. Though I don't recommend it:

while (true) {
  String aLine = infile.readLine();
  if (aLine==null) {
     System.out.println("No more lines. Will exit the loop");
     break;
  }
  // no else needed here because if you go in the above if, you will break from the loop and nothing else will execute.
  // with the break command you exit the loop

  System.out.println("Line:"+aLine);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.