End of file NullPointerException - java

What I wanted is to reach EOF by typing Ctrl + z from command line with BufferedReader reading from console. The following code does so. But the problem is, it issues a NullPointerException after reaching EOF. Is there a way to skip this exception? Or more precisely, what is the proper way of reaching EOF with BufferedReader reading from console?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class EOF {
public static void main(String args[]) {
String s = "";
String EOF = "^z";
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try {
while (!s.equals(EOF)) {
s = read.readLine();
}
} catch (IOException e) {}
}
}

Or more precisely, what is the proper way of reaching EOF with bufferedReader reading from console?
Currently you're actually detecting the characters '^' and 'z' it's not like '^' is really a control character.
The exception you're getting is actually a hint as to how you should be handling this. From the docs for BufferedReader.readLine:
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So basically you should loop until readLine returns null.
String line;
while((line = read.readLine()) != null)
{
// Do something with line
}

See how much a debugger can help:
After I press ctrl + z, s has null value, hence you're getting this exception, since it's like writing !null.equals(EOF).
Why?
Because BufferedReader#readLine returns "null if the end of the stream has been reached".

Just use null as EOF signal.
while((s=read.readLine())!= null)
{
.....
}

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String str;
while((str=input.readLine()) != null ) {
//
}

Related

Error occurred When I execute my code

I beginner to Java, I want to read and write a string from a text file, I tried with my idea but its not work. It show me an error...
See below my code:
import java.util.*;
import java.io.*;
public class Uptime {
public static void main(String[] args) {
FileWriter fileWriter = null;
try
{
double Oldtime=0;
BufferedReader read=new BufferedReader(new FileReader("C:/eGurkha/agent/sample/UptimeRecord.txt"));
if(read.readLine()!=null)
{
Oldtime=Double.parseDouble(read.readLine());
System.out.println("Old System Time is :"+Oldtime);
}
else
{
Oldtime=0;
}
Process p=Runtime.getRuntime().exec("C:\\eGurkha\\lib\\vmgfiles\\win\\VmgUptimeTest.exe");
BufferedReader rd=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=rd.readLine();
System.out.println(line);
String[] word=line.split("=");
fileWriter=new FileWriter("C:/eGurkha/agent/sample/UptimeRecord.txt");
fileWriter.write(word[1]);
System.out.println("New System Time is :"+word[1]);
System.out.println("String Written");
fileWriter.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
This is the error, which is shown by the above code.
Exception in thread "main" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1008)
at java.lang.Double.parseDouble(Double.java:540)
at com.kavi.tasks.Uptime.main(Uptime.java:17)
Please tell me the idea...
The problem is the code
if(read.readLine()!=null)
{
Oldtime=Double.parseDouble(read.readLine());
You read line (it isn't null) but then you read the next line when try to parse (and the next line is empty).
Use instead
String line=read.readLine();
if(line!=null)
{
Oldtime=Double.parseDouble(line);
if(read.readLine()!=null)
{
Oldtime=Double.parseDouble(read.readLine());
System.out.println("Old System Time is :"+Oldtime);
}
You're reading the line in the if-statement. Then you read the next line in the parseDouble-statement. This is reference is null. So you've to save the line in the if statement.
String line = null;
if((line = read.readLine()) != null) {
double time = Double.parseDouble(line);
...
}
Try to Pass the String in the if statement ,so that the compile would know that which type of object he needs to pass.
if(String=....
.....){
}
problem is with
if(read.readLine()!=null)
{
Oldtime=Double.parseDouble(read.readLine());
System.out.println("Old System Time is :"+Oldtime);
}
readLine() internally calls lineNumber++ which means you go to next line of your file when you call this. Instead use
if((line = read.readLine()) != null)
{
Oldtime=Double.parseDouble(line);
System.out.println("Old System Time is :"+Oldtime);
}

BufferedReader reads a value which is somehow null

Ok, so I was doing a program which has a config file handler, and what it does is that it reads in the lines from a text file, which looks something like this:
ImagePath=SomePath
The method reads line by line matching the key with the corresponding line, and after that it then searches for the '=' character position in the String, and then substrings it such that the value SomePath is obtained. However, there is an issue.
Basically, the issue I am facing is that the reader is able to read the file, as I put a statement to print out the lines variable and it does print out the line read. However, the issue is that this lines variable would then be manipulated, but an NullPointerException error would occur around there (the lines.substring(0,key.length()-1) part), suggesting that the lines variable suddenly became null even though it is shown that something was read into the variable. Thing is, what happens to this variable in between the print statement and the string manipulation? I am unable to fix this issue. Pardon my code which might look messy or whatnot. I was trying multiple variations of my code to try to mitigate the issue, but it seems to not work. What is shown below is my latest variation of the code.
public static String readConfig(String key) throws IOException
{
BufferedReader reader=null;
try
{
reader=new BufferedReader(new FileReader(config));
}
catch(FileNotFoundException e)
{
System.out.println("Failed to read file. Code: 3");
System.exit(0);
}
String lines=reader.readLine();
System.out.println(lines);
String returnValue=null;
while(true)
{
if(key.equals(lines.substring(0,key.length()-1)))
{
int plusPos=0;
for(int i=0;i<lines.length();i++)
{
if(lines.charAt(i)=='=')
{
plusPos=i;
}
}
if(plusPos==0)
{
reader.close();
return null;
}
returnValue=lines.substring(plusPos,lines.length()-1);
reader.close();
return returnValue;
}
lines=reader.readLine();
}
}
Edit 1: Ok, I see that Sbodd suggested that my code is kinda flawed, but well, the above snippet is just an instance to debug and test exactly which part of the loop does the line variable suddenly read null. Here is my original code snippet:
public static String readConfig(String key) throws IOException
{
BufferedReader reader=null;
try
{
reader=new BufferedReader(new FileReader(config));
}
catch(FileNotFoundException e)
{
System.out.println("Failed to read file. Code: 3");
System.exit(0);
}
String line;
String returnValue;
while((line=reader.readLine())!=null)
{
line=line.trim();
if(key.equals(line.substring(0,key.length()-1)))
{
int plusPos=0;
for(int i=0;i<line.length();i++)
{
if(line.charAt(i)=='=')
{
plusPos=i;
}
}
if(plusPos==0)
{
return null;
}
returnValue=line.substring(plusPos,line.length()-1);
return returnValue;
}
}
return null;
}
Your code will always throw a NPE when it reaches the end of the file.
From the documentation for BufferedReader:
[readLine returns] A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.
Since your code is:
lines = reader.readLine();
while (true) {
//do stuff with lines
lines=reader.readLine();
}
when you reach end-of-file, reader.readLine will return null, you'll still pass your while check (since "true" is always true), and then you'll try and use that null pointer.
You could just replace while(true) with while (lines != null).
A typical pattern to do this instead would be
while ((lines = reader.readLine()) != null) {
//do stuff with lines
}
(Note that here, you don't make the first call to readLine outside the while loop, since your condition will be tested before the first execution of the loop.)
Your string comparison will always fail.
if(key.equals(lines.substring(0,key.length()-1)))
Will attempt to match "ImagePat" and "ImagePath", which will fail. This will then cause a second iteration of the loop, with lines now equal to null.
Your comparison should be:
if (key.equals(lines.substring(0, key.length())))
Also, your return value should be
returnValue = lines.substring(plusPos + 1, lines.length());
to properly return the value.
You should also look at the Properties class, it will make things a lot easier.

Looping over InputStream truncating data

So this is a very simple problem with a simple solution that I'm just not seeing:
I'm trying to get a list of data through an InputStream, looping until I reach the end of the stream. On each iteration, I print the next line of text being passed through the InputStream. I have it working but for one small problem: I'm truncating the first character of each line.
Here's the code:
while (dataInputStream.read() >= 0) {
System.out.printf("%s\n", dataInputReader.readLine());
}
And the output:
classpath
project
est.txt
Now, I know what's going on here: the read() call in my while loop is taking the first char on each line, so when the line gets passed into the loop, that char is missing. The problem is, I can't figure out how to set up a loop to prevent that.
I think I just need a new set of eyes on this.
readLine for DataInputStream is deprecated. You may try wrapping it with a BufferedReader:
try
{
String line;
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( dataInputStream ) );
while( (line = bufferedReader.readLine()) != null )
{
System.out.printf("%s\n", line);
}
}
catch( IOException e )
{
System.err.println( "Error: " + e );
}
Also, I`m not sure, that it is a good idea to use available() due to this specification:
* <p>Note that this method provides such a weak guarantee that it is not very useful in
* practice.
Use one BufferedReader and InputStreamReader, here is one example:
InputStream in=...;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while (br.ready()) {
String line = br.readLine();
}
dataInputStream.read() reads the first character of the InputStream, the same as dataInputReader.readLine() reads the complete next line. Every read character or line is then gone. you can use the dataInputStream.available() to check if the InputStream has data available.
That should print the correct output:
while (dataInputStream.available()) {
System.out.printf("%s", dataInputReader.read());
}
String line;
while ((line = dataInputReader.readLine()) != null) {
System.out.println(line);
}

Bufferedreader explanation?

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.in(Standard input stream)- gets the input from keyboard in bytes
InputStreamReader: Converts the bytes into Unicode characters/ converts the standard input into reader object to be used with BufferedReader
Finally BufferedReader: Used to read from character input stream(Input stream reader)
String c = br.ReadLine(); -- a method used to read characters from input stream and put them in the string in one go not byte by byte.
Is everything above right ? Please correct if anything wrong !
Nearly there, but this:
String c = br.readLine(); -- a method used to read characters from input stream and put them in the string in one go not byte by byte.
It reads characters from the input reader (BufferedReader doesn't know about streams) and returns a whole line in one go, not character by character. Think of it in layers, and "above" the InputStreamReader layer, the concept of "bytes" doesn't exist any more.
Also, note that you can read blocks of characters with a Reader without reading a line: read(char[], int, int) - the point of readLine() is that it will do the line ending detection for you.
(As noted in comments, it's also readLine, not ReadLine :)
What is the purpose of BufferedReader, explanation?
Bufferedreader is a java class, the following is the hierarchy of this class.
java.lang.Object ==> java.io.Reader ==> java.io.BufferedReader
Also, BufferedReader provides an efficient way to read content. Very Simple..
Let's have a look at the following example to understand.
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
BufferedReader contentReader = null;
int total = 0; // variable total hold the number that we will add
//Create instance of class BufferedReader
//FileReader is built in class that takes care of the details of reading content from a file
//BufferedReader is something that adds some buffering on top of that to make reading fom a file more efficient.
try{
contentReader = new BufferedReader(new FileReader("c:\\Numbers.txt"));
String line = null;
while((line = contentReader.readLine()) != null)
total += Integer.valueOf(line);
System.out.println("Total: " + total);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally{
try{
if(contentReader != null)
contentReader.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
}

while EOF in JAVA?

Following to some forums answers I'm using this:
while (fileReader.nextLine() != null) {
String line = fileReader.nextLine();
System.out.println(line);
}
... but it throws exception at the end anyway
(Exception in thread "main" java.util.NoSuchElementException: No line found)
Each call to nextLine() moves onto the next line, so when you are actually at the last readable line and the while check passes inspection, the next call to nextLine() will return EOF.
Perhaps you could do one of the following instead:
If fileReader is of type Scanner:
while ((line = fileReader.hasNextLine()) != null) {
String line = fileReader.nextLine();
System.out.println(line);
}
If fileReader is of type BufferedReader:
String line;
while ((line = fileReader.readLine()) != null) {
System.out.println(line);
}
So you're reading the current line in the while condition and saving the line in a string for later use.
you should use while (fileReader.hasNextLine())
To read a file Scanner class is recommended.
Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
try {
while (scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
}
finally{
scanner.close();
}
The others told you enough about your issue with multiple calls of readLine().
I just wanted to leave sth about code style:
While you see this line = assignement and != null check together in one while condition in most examples (like #gotomanners example here) I prefer using a for for it.
It is much more readable in my opinion ...
for (String line = in.readLine(); line != null; line = in.readLine()) {
...
}
Another nice way to write it you see in #TheCapn's example. But when you write it that way you easily see that's what a for-loop is made for.
I do not like assignments scrambled with conditions in one line. It is bad style in my opinion. But because it is so MUCH popular for that special case here to do it that way I would not consider it really bad style. (But cannot understand who established this bad style to become that popular.)
The problem is that you're reading nextLine() on the while loop and THEN reading it to a variable. Not only are you getting every 2nd line printed out you're opening yourself to the exception being thrown. An example:
File:
Hello,
Blah blah blah,
Sincerely,
CapnStank
PS. Something something
On first iteration through the loop. The check on while will consume the "Hello," as not equal to null. Inside the loop body you'll see Blah blah blah, printed to the System.
The process will repeat with Sincerely, being consumed and Capnstank printing out.
Finally the while will consume the "PS" line while the String line = fileReader.nextLine() retreives an exception from the file because there's nothing further to read.
To resolve the issue:
String line = fileReader.nextLine();
while (line != null) {
System.out.println(line);
line = fileReader.nextLine();
}
nextLine() will throw an exception when there's no line and it will never return null,you can try the Scanner Class instead : http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
while(inFile.hasNext())
This is correct in java programming language
//By: Ishraga Mustafa Awad Allam
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class B_C_Data {
public static void main(String[] args) {
try {
// Create a file reader
FileInputStream fr = new FileInputStream(args[0]);
// Create a file output stream
DataInputStream dr = new DataInputStream(fr);
// Read and display data
while (dr.available() > 0) {
System.out.println(dr.readDouble());
}
// Close file input stream
dr.close();
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}

Categories