Reputation: 1178
I am having trouble seeing what is wrong with the code below. It is outputting nulls when there aren't any.
output: null This is one. This is two. This is three. This is four five six. seven? null
The contents of the file:
This is one.
This is two.
This is three.
This is four
five
six.
seven?
Any help on this would be greatly appreciated!
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String cLine="";
while ((cLine = br.readLine()) != null) {
content+= cLine;
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(content);
Upvotes: 3
Views: 258
Reputation: 488
Just a comment...
I didn't know this syntax of try. Initially I thought it was a typo but I found that it actually works ( I compiled it and ran the code).
I thought it was always : try { .... .... .... } catch() {}
on further reading, found that this was a new feature of Java 7 , "try with resource" (from Special syntax of java try catch block)
Upvotes: 0
Reputation: 433
If your starting out with Java I suggest something simpler... like using a Scanner on the file instead. Ponder the following:
Scanner fileRead = new Scanner(fileName);
while ( fileRead.hasNextLine() ) {
System.out.println( fileRead.nextLine() );
}
My suggestion anyways.
Upvotes: -2
Reputation: 1500595
I suspect content
is null to start with (rather than empty) which explains the first null
. It doesn't explain the last one, admittedly... My guess is that you've actually fixed a bug since you saw the output with null
at the end. Either that or your file actually has null
at the end. (I've tested it with content
initialized to "" and it's fine.)
Are you aware that you're removing all line breaks though, and not replacing them with any kind of delimiter? So a file with lines of "x", "y" and "z" will become just "xyz".
Additionally, consider using a StringBuilder
rather than string concatenation - it'll be more efficient as it won't need to copy the string all the time.
Upvotes: 7