while EOF in JAVA? - 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);
}
}
}

Related

How to only read in lines from a textfile if they fit a specific criteria?

I have a text file that I can now scan, however there are certain lines within the file that I don't want to read in, is there a way to only read in a line if it starts with a capital letter?
Please help a nooby?
Pretty straightforward problem, pretty simple solution:
try (BufferedReader br = new BufferedReader(new FileReader("filename.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(!line.isEmpty() && Character.isUpperCase(line.charAt(0)))
System.out.println(line);
}
}
catch(Exception e){
// Handle the trouble
}
Simply check if the line you just read (provided non-empty and not null as checked in the if-statement) starts with an uppercase letter, otherwise it will move on to the next line.

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);
}

How to read a specific line in a text file and return a part of it?

I have several strings in a file where I am supposed to stop and read the values from those strings. For example:
This is the first line
#1 stop = 300
This is the third line
This is the 4th line
#2 stop = 400
This is the 6th line
I need to stop at #1 and extract the value 300 from there. Then I have to stop at #2 and extract 400, and so on.
I am VERY new to Java and can't figure out what is wrong with my code. (I haven't gotten to extracting the values yet):
public static void main(String[] args) throws IOException {
//read
File fromFile = new File("in.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader(fromFile));
String line;
String firstHandler="";
while ((line = bufferedReader.readLine()) != null) {
bufferedReader.readLine();
if (firstHandler.startsWith("#1")){
System.out.println(firstHandler);
String[] parts = firstHandler.split("=");
System.out.println(Arrays.toString(parts));
}
break;
}
System.out.println(line);
bufferedReader.close();
}
}
At this point it only prints the first line, which is not at all what I need. Can anyone explain to me how this should be done in the right way?
The errors are in these 4 lines:
String firstHandler="";
while ((line = bufferedReader.readLine()) != null) {
bufferedReader.readLine();
if (firstHandler.startsWith("#1")){
You read one line from inside the while statement. And for each line read, you enter the block. But inside this block, you read yet another line.
And then, what you compare with "#1" is not the line that you have just read, but firstHandler, which is initialized as an empty string once, and never modified. The code should be:
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("#1")) {
The reader should also be closed in a finally block, but that's another matter.
First of all, as pointed out in the comments, you need to match lines starting with a #, since there are multiple lines beginning with # but having a different second character.
Next, you need to check the value of the line that you are reading to check for the # character. So, you can get rid of the firstHandler variable and use the line variable instead.
Finally, you need to get rid of the break statement, since that causes the loop to exit after the first line itself. That is the reason you only see the first line on the screen.
Therefore, your code can be changed to something like this:
while ((line = bufferedReader.readLine()) != null)
{
if (line.startsWith("#"))
{
System.out.println(line);
String[] parts = line.split("=");
System.out.println(Arrays.toString(parts));
}
}

End of file NullPointerException

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 ) {
//
}

How can I read text appended to the end of a file I already read?

I want to read a text file in Java. After I finish, some text will be appended by another application, and then I want to read that. Lets say there are ten lines. When the other app appends one more line, I dont want to read the whole file again; just the new line. How can I do this?
Something like this could work:
BufferedReader reader = .. // create a reader on the input file without locking it
while(otherAppWritesToFile) {
String line = reader.readLine();
while(line != null) {
processLine(line);
line = reader.readLine();
}
Thread.sleep(100);
}
Exception handling has been left out for the sake of simplicity.
Once you get an EOF indication, wait a little bit and then try reading again.
Edit: Here is teh codez to support this solution. You can try it and then change the control flow mechanisms as needed.
public static void main(final String[] args) throws IOException {
final Scanner keyboard = new Scanner(System.in);
final BufferedReader input = new BufferedReader(new FileReader("input.txt"));
boolean cont = true;
while (cont) {
String line = input.readLine();
while (line != null) {
System.out.println(line);
line = input.readLine();
}
System.out.println("EOF reached, add more input and type 'y' to continue.");
final String in = keyboard.nextLine();
cont = in.equalsIgnoreCase("y");
}
}
EDIT: Thanks for adding some code Tim. Personally, I would just do a sleep instead of waiting for user input. That would more closely match the users' requirements.
You could try using a RandomAccessFile.
Open the file and then invoke the length() to get the length of the file. Then you can use the readLine() method to get your data. Then the next time you open the file you can use the seek() method to position yourself to the previous end of the file. Then read the lines and save the new length of the file.

Categories