Reader readline null java

getting null when reading a text file in java using buffered reader

I’m having a problem reading a text file in java and assigning it to an array. The program is running but I’m getting null. I tried changing the code to its simplest for just like what you see below. Because this one should really loop through the text file. But I’m doing it this way so that I will easily see where’s the problem. But the problem is that I don’t know why is it still outputting null. The file is certainly in the directory I’ve specified since the built in method exists returned true when I check it using this one:

public static void main(String args[])< String[] eq=new String[50]; String[]ea=new String[50]; String[]eb=new String[50]; String[] ec=new String[50]; String[]ed=new String[50]; char[] ans=new char[50]; String strtemp; File ofile= new File("J:\\questions.txt"); BufferedInputStream bis= null; FileInputStream fis= null; DataInputStream dis=null; int ii=0; int score=0; System.out.println(eq[1] + "\n" + ea[1] + "\n" + eb[1] + "\n" + ec[1] + "\n" + ed[1] + "\n" + "\n" + "Answer: "); String strans=x.nextLine(); char y=strans.charAt(0); if(y==ans[1])< score++; >else < >try < fis=new FileInputStream(ofile); bis=new BufferedInputStream(fis); dis=new DataInputStream(bis); while(dis.available()!=0)< eq[1]=dis.readLine(); ea[1]=dis.readLine(); eb[1]=dis.readLine(); ec[1]=dis.readLine(); ed[1]=dis.readLine(); strtemp=dis.readLine(); ans[1]=strtemp.charAt(0); >bis.close(); dis.close(); fis.close(); >catch(FileNotFoundException e)< e.printStackTrace(); >catch(IOException e) < e.printStackTrace(); >> 

3 Answers 3

Here’s how you read a text file in Java using BufferedReader:

 BufferedReader reader = null; try < reader = new BufferedReader( new FileReader( "J:\\questions.txt") ); String line = null; do < line = reader.readLine(); if( line != null ) < // Do Something with line >> while( line != null ); > catch (Exception e) < e.printStackTrace(); >finally < if( reader != null ) try < reader.close(); >catch (IOException e) < >> 

I think i had a similar problem. As far as i could tell the dis.available returns 0 even if there is text to read. Try to read something in a buffer.

Читайте также:  Deep first search python

+1. If you’re ever using available() and functionally relying on what it returns, you’re probably doing something wrong. Always returning 0 is a perfectly compliant implementation of available() .

`available’ is described in the javadoc as

int available() Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

It’s initially going to be 0 because you haven’t read from it yet. Don’t use available for this.

Источник

Reading lines with BufferedReader and checking for end of file

How can I avoid a crash if the next line is the end of the file? (i.e. null) I need to read the next line because there may be something there that I need to deal with but if there isn’t the code just crashes. If there is something there then all is OK, but I can’t be guaranteed that there will be something there. So if I do something like: (pseudo code):

if (r.readLine is null) //End code else

The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again? I’ve not worked out a way to do this — any suggestions would be a great help.

Really wish people would leave a reason when down-voting. A down-vote is supposed to indicate there is something wrong with a question so maybe it can be reformatted. Down-voting without leaving a reason as to why the downvote has been cast helps no-one

8 Answers 8

Am. You can simply use such a construction:

String line; while ((line = r.readLine()) != null) < // do your stuff. >

If you want loop through all lines use that:

while((line=br.readLine())!=null) < System.out.println(line); >br.close(); 

You can use the following to check for the end of file.

public bool isEOF(BufferedReader br) < boolean result; try < result = br.ready(); >catch (IOException e) < System.err.println(e); >return result; > 

This fails silently on exception and BufferedReader::ready can return false even if the next read will succeed.

In your case you can read the next line because there may be something there.If there isn’t anything, your code won’t crash.

String line = r.readLine(); while(line!=null)

A question in the first place, why don’t you use «Functional Programming Approach«? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-

import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; public class LineOperation < public static void main(String[] args) throws IOException < Files.newBufferedReader(Paths.get("C://xyz.txt")). lines(). collect(Collectors.toSet()). // You can also use list or any other Collection forEach(System.out::println); >> 

Источник

BufferedReader is initialised but readLine returns null?

I have a class measurementFile its constructor is posted below. and in the class File_IO_03 which has the main method, i instantiate an object of the afrementioned class but when I try to readLine using mf.getbR.readLine te console displays null. To note: mf is te object of the formerly mentioned class and getbR() is a method in that class that should return a bufferedReader object initialised. Below is my attempt to read a line frm a file using bufferedReader Code:

**File_IO_03**: File f = new File(path); MeasurementFile mf = new MeasurementFile(f, MeasurementFile.ENCODING_ISO_8859_1); if ( (mf.getiS() == null) || (mf.getbR() == null) ) < System.out.println("either iS or bR is null"); >else < System.out.println("both iS or bR are initialised"); // successful System.out.println("path: " + mf.getFile().getAbsolutePath());// displayed System.out.println("" + mf.getbR().readLine()); // this returns null System.out.println("total lines in the file: " + mf.getTotalLines());// successful readLines(mf, 4); //readLines(mf, 6); //continueReading(mf); >private static void readLines(MeasurementFile mf, int lines) throws IOException < // TODO Auto-generated method stub /*InputStream is = new FileInputStream(mf.getFile()); mf.setiS(is); BufferedReader br = new BufferedReader(new InputStreamReader(mf.getiS())); mf.setbR(br);*/ String line; int linecounter = 0; while ((line = mf.getbR().readLine()) != null) < System.out.println("current line read: " + line); if (++linecounter == lines) < mf.getbR().mark(0); System.out.println("mark set at linecounter: " + linecounter + "lines: " + lines); break; >> > 
 public MeasurementFile(File file, Charset encoding) throws IOException < this.setFile(file); //if (this.myFile.setReadOnly()) this.getFile().setReadable(true); this.getFile().setWritable(true); if (this.getiS() == null) < this.iS = new FileInputStream(this.getFile()); this.setiS(this.iS); >if (this.getbR() == null) < this.bR = new BufferedReader(new InputStreamReader(this.getiS())); this.setbR(this.bR); >this.totalLines = countTotalLines(); if (this.getTotalLines() > 0) < this.fileToHash(); this.splitFileIntoPages(); >else System.out.println("@MeasurementFile(): The file is empty can not create more data"); > 

Источник

Using BufferedReader.readLine() in a while loop properly

The file I am reading from is 100 lines of arguments. If I use a for loop it works perfectly. If I use the while statement (the one commented out above the for loop) it stops at 50. There is a possibility that a user can run the program with a file that has any number of lines, so my current for loop implementation won’t work. Why does the line while(br.readLine()!=null) stop at 50? I checked the text file and there is nothing that would hang it up. I don’t get any errors from the try-catch when I use the while loop so I am stumped. Anyone have any ideas?

7 Answers 7

try < InputStream fis=new FileInputStream(targetsFile); BufferedReader br=new BufferedReader(new InputStreamReader(fis)); for (String line = br.readLine(); line != null; line = br.readLine()) < System.out.println(line); >br.close(); > catch(Exception e)

This is the way to go for me. while((line=br.readLine())!=null) is just too ugly. I don’t like calling br.readLine() twice but there is not much you can do about that. I would just shorten the for statement to for (String s = br.readLine(); s != null; s = br.readLine())

I like the for loop syntax so you don’t have a variable hanging around after the loop. Also it can be shortened a bit, still kind of ugly: for ( String line = null; null != (line = reader.readLine()); ) Note: using reader.readLine() in the conditional and the initializer of the for causes the first line to be skipped.

I don’t know java well, so this is probably not the cleanest fix, but when a program can’t open a file, it should give a useful error message explaining why. In other words, don’t throw away important information; include it in the error message. eg, System.err.println(«Error: Target File Cannot Be Read» + e);

doesn’t it take a lot of memory because in every loop its creating a string object and assigning the reference «line» to that object and also leaving the older string object to be garbage collected. We all string is immutable . can’t we use StringBuilder in some way

Источник

readline() returns null in Java

I’m trying to read the stdin in my Java program. I’m expecting a series of numbers followed by newlines, like:

When providing the input through the eclipse built-in console, everything goes well. But when using the Windows command line, the program prints:

Received '6'. Received 'null'. Invalid input. Terminating. (This line is written by another function that does an Integer.parseint()). 
static String readLineFromStdIn()< try< java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); String input = new String(); input = stdin.readLine(); System.out.println("Received '" + input + "'"); return(input); >catch (java.io.IOException e) < System.out.println(e); >return "This should not have happened"; > 

I enter the input in the Eclipse console, all numbers followed by enter. In windows I do «java -jar program.jar < input.txt". I have tried saving this 'input.txt' file both in UNIX and Windows coding. Didn't help.

2 Answers 2

That you get a null indicates that the relevant Reader objects reached an EOF (end of file), or in other words that they can’t get any more standard input. Now the obvious issues with your code are:

  1. Each method call to readLineFromStdIn() will create a new BufferedReader .
  2. Each such BufferedReader will be “competing” with each other for the same, shared input from System.in
  3. And none of these BufferedReader objects are ever properly closed, so your program leaks I/O resources with each call to readLineFromStdIn() .

The solution is to use a single shared BufferedReader object for each invocation of readLineFromStdIn() .

Every time you open up a stdin , it technically means you’re opening a file stream and you’re never closing it which overshoots the possible number of open file connections that Java can hold.

@user268396 Note that if this BufferedReader were closed it would also close System.in which may not be desirable. This could be a rare case where you just want the decorator streams to be GC’d without being closed.

Agreed you don’t want to cause System.in to be closed explicitly. However it will be closed anyway when the BufferedReader is GC’ed. There are finalizers to that extent, IIRC. I guess what happened before the fix was that on the Windows VM the temporary BufferedReader objects were GC’ed very agressively and hence caused STDIN to be closed before the second readLineFromStdIn call (hence the null, trying to read from a closed System.in ).

Not really a new answer to this question, but I wanted to clear up confusion in the comments about why the original code behaved as it did (I can’t comment because I’m new to ST and haven’t garnered reputation points).

The null result has nothing to do with garbage collection. The following program suffers exactly the same fate even though both readers still live, accessible objects:

BufferedReader r1 = new BufferedReader(new InputStreamReader(System.in)); System.out.println(r1.readLine()); BufferedReader r2 = new BufferedReader(new InputStreamReader(System.in)); System.out.println(r2.readLine()); 

It all comes down to what «Buffered» means in BufferedReader . It’s a Reader that includes internal buffering. The internal buffering usually significantly improves the efficiency of operations on the underlying stream, e.g. by attempting to read a full buffer’s worth each time, rather than nickle-and-diming the stream to death getting a few bytes here and a few there.

So what happens when you create the first BufferedReader on stdin and read a line from it? That BufferedReader reads a buffer-full from the stream, detects the end of line, returns the first line, and hangs on to the rest of the buffer to fill its next request. That leaves the underlying stream positioned beyond the end of that first line. And if your input is small, it could easily be positioned at EOF.

So now you come along and create a second BufferedReader atop the same stream — which is at EOF — and attempt to get a line. The second BufferedReader attempts to read from the underlying stream and detects EOF, so readLine returns null .

Источник

Оцените статью