Reputation: 606
I have a more complex program that involves using what's written in a text file but it wasn't working at all, nothing was being displayed and everything is dependent on the file. If i just make the string equal to something in my code and get rid of reading from the file then it works. I tried something as simple as displaying the line that is read but it doesn't display anything when i run it.
Edit: It can't find the path to the file... where is the default file usually in? The file is in the same directory as the program but it can't find it, why?
public static void main(String[] args) {
String s;
try {
FileReader fstream=new FileReader("input.txt");
BufferedReader in=new BufferedReader(fstream);
while((s=in.readLine())!=null){
System.out.print(s);
}}catch(IOException e){
System.exit(0);
}
}
}
Upvotes: 0
Views: 69
Reputation: 8139
As others have mentioned, you are incorrectly reading lines at twice the rate of inspection. Their solutions address the root of the problem.
However, if memory isn't a concern and you are using Java 7, you may be interested in Files.readAllLines
List<String> lines = Files.readAllLines(path, Charset.defaultCharset() );
From the docs:
Read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset... Note that this method is intended for simple cases where it is convenient to read all lines in a single operation. It is not intended for reading in large files.
The benefit of using this method is that it abstracts the details, handles closing the file for you and is generally easier to use.
Upvotes: 0
Reputation: 2202
You're reading two lines every time the loop repeats. Remove the
s=in.readLine();
contained in the loop.
Upvotes: 0
Reputation: 347334
Your performing a double read
while((s=in.readLine())!=null){
s=in.readLine();
You read the line in within the while condition, then try and read another line immediately after it, presumably hitting the end of the file
Try removing the second in.readLine() statement
Upvotes: 1
Reputation: 692181
Don't ignore exceptions. If nothing is read, it's probably that an exception is thrown. Instead of letting it bubble and telling you what's wrong, you catch it and exit silently. That's like buying a fire alarm and setting its sound volume to 0: you'll never know there is a fire.
Transform your program to
public static void main(String[] args) throws IOException {
String s;
FileReader fstream=new FileReader("input.txt");
BufferedReader in=new BufferedReader(fstream);
while((s=in.readLine()) != null) {
System.out.print(s);
}
}
and see what happens.
Also, I removed the call to readLine() inside the loop. The line has already been read at this point.
Upvotes: 3