Using the following code to split the output of a reader into strings which are then used in a constructor. However when the bufferreader reaches the end of the stream it outputs null, which then causes a null pointer exception in the constructor.
List<Pattern> resultList = new LinkedList<Pattern>();
BufferedReader buff = new BufferedReader(r);
String current;
while (buff != null) {
current = buff.readLine();
System.out.println(current);
Pattern p = new Pattern(current);
resultList.add(p);
}
return resultList;
I've tried putting an if statement to test if the current string is null, however I don't know what to put in the body of the if-clause. Any help would be greatly appreciated
buff is never going to be null - it's the return value of readLine which is null when you reach the end of the data. That's what you need to check, typically with code which assigns the value to a variable and checks it in one go:
String current;
while ((current = buff.readLine()) != null) {
System.out.println(current);
Pattern p = new Pattern(current);
resultList.add(p);
}
Instead of putting an if into the while, change the conditions of your loop from:
while (buff != null)
to:
while ((current = buff.readLine()) != null)
buff will not become null as a result of reaching the end of the stream, but current will become null when there is no more input to be returned
Related
I'm not entirely sure what the issue is, but here is a snippet of my code. I get the warning for my line variable
StringBuffer stringBuffer = new StringBuffer();
String line = "" ;
while(( line = bufferedReader.readLine()) != null ){
stringBuffer.append(line);
}
The warning simply means that the empty string with which the line variable is initialized is useless.
Before line is read, it is being assigned in the loop declaration:
line = bufferedReader.readLine()
So assigning line = "" is redundant. You can leave it uninitialized:
String line;
while((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
Append to #ernest_k answer, assigning line = "" is redundant only if you reassign line with another value and you don't use line in return statement or set statement (set value need at least null value).
I am using a buffered reader to read a file. I need to call trim on all of these lines to pass tests my professor has given us. The problem is there are a few lines that are empty strings, so how I have it set up I am getting a null pointer exception. My biggest question is there away with buffered readers that I can check make sure the line is not an empty String. Thank you for what ever help you have!
FileReader fRead = new FileReader(bibleFile);
BufferedReader bRead = new BufferedReader(fRead);
String line = bRead.readLine();
if (!line.equals("")) {
line = bRead.readLine().trim();
while (line != null) {
/** method * */
line = bRead.readLine().trim();
}
}
bRead.close();
Check the line whether null or not:
String str;
while ((str = bRead.readLine()) != null) {
}
You need to check whether line is null or not before check it's empty or not
So I tracked down the bugger, but I am no closer to understanding what is wrong. Here is what the compiler says:
Exception in thread "main" java.lang.NullPointerException at
BasicFile.Search(BasicFile.java:215) at
TestFile.main(TestFile.java:42)
Line 215 is the one that starts with while, first one.
String Search(String key) throws IOException {
int lines = 0;
String line = "";
String foundAt = "";
BufferedReader BF = new BufferedReader(new FileReader(f));
try {
while ((line = BF.readLine().toLowerCase()) != null) {
lines++;
//create tokenizer words with what is in line
StringTokenizer words = new StringTokenizer(line);
while(words.hasMoreTokens()) { //while words has tokens left
//go to next token and compare to key
if (words.nextToken().equals(key.toLowerCase()))
foundAt = foundAt + "\n" + lines + ":" + line;
//do nothing continue loop
}
}
BF.close();
} catch(FileNotFoundException e) {
}
return foundAt;
}
When your buffer reader runs out of lines it returns null. You are trying to call toLowerCase method on null which ends up throwing the null pointer exception.
Refactor your code in a way that it doesn't require you to execute toLowerCase before ensuring the line is non-null.
For example:
String next;
while ((next = BF.readLine()) != null) {
String line = next.toLowerCase();
// ...
}
while ((line = BF.readLine().toLowerCase()) != null)
What happens if BF.readline() returns null?
remove .toLowerCase() from the test
Please, stop it, your code is giving me cancer! There are a number of stylistic errors in the code that you need to fix.
First off in java, method names always begin with a lowercase letter. You are programming in Java, not C#, so you need to use the Java naming conventions. That means your method should be called search, not Search.
The same goes for variable names. What is BF supposed to mean, anyway? Replace it with in, please.
Next up, unless this method is in an object that itself represents that particular file, the global variable f should be passed as a parameter instead.
BufferedReader is AutoCloseable, so you should use a try-with-resources to deal with closing it.
You need to add a javadoc comment to it, documenting its parameters with #param, its return with #return, and exactly why it might need to throw an IOException with #exception.
Here is a mostly-fixed version of your code:
/**
* Needs Javadoc
*/
String search(String key, File f) throws IOException {
int lines = 0
String line = "";
String foundAt = "";
try(BufferedReader in = new BufferedReader(new FileReader(f)) {
while ((line = in.readLine().toLowerCase()) != null) { //the line in question
lines++;
StringTokenizer words = new StringTokenizer(line);
while(words.hasMoreTokens())
if (words.nextToken().equals(key.toLowerCase()))
foundAt = foundAt + "\n" + lines + ":" + line;
}
} catch(FileNotFoundException e){}
return foundAt;
}
Now, the problem here is that in.readline() returns a null sometimes. Calling a method on a null is always a NullPointerException. Therefore you get a NullPointerException when you attempt to call that null's missing toLowerCase() method.
You need to convert it toLowerCase after you ensure it is non-null.
I am reading an entire file and I want to use the line if it contains a specific string. I am unable to use the string because it is printing null outside the while loop, despite the fact that I have initialized it outside the loop.
FileInputStream wf = new FileInputStream(pr.getSplitDir() + listfiles[i]);
BufferedReader wbf = new BufferedReader(new InputStreamReader(wf));
String wfl = "";
while ((wfl = wbf.readLine()) != null) {
if (wfl.contains("A/C NO:")){
// System.out.println(wfl); // Here it is Printing the correct line
}
}
System.out.println(wfl); // Here it is printing null
Please help.
Try this below, You have to use another String or StringBuilder to get final out put
FileInputStream wf = new FileInputStream(pr.getSplitDir() + listfiles[i]);
BufferedReader wbf = new BufferedReader(new InputStreamReader(wf));
String wfl = "";
StringBuilder sb = new StringBuilder();
while ((wfl = wbf.readLine()) != null) {
if(wfl.contains("A/C NO:")){
//System.out.println(wfl);//Here it is Printing the correct line
sb.append(wfl);
}
}
System.out.println(sb.toString());//Here it is printing null
while ((wfl = wbf.readLine()) != null) {
if(wfl.contains("A/C NO:")){
//System.out.println(wfl);//Here it is Printing the correct line
}
}
Your while loop will exit only when wfl is null. So you have your answer!
To stop, your loop need wfl to be null, so when your loop has just stopped, wfl is obviously null.
Because your wbf.readLine when read null ,it assigns it wfl too and then compares to null
while ((wfl = wbf.readLine()) != null) { // here wbf.readLine when read null assigns to wfl
if(wfl.contains("A/C NO:")){
//System.out.println(wfl);//Here it is Printing the correct line
}
}
Do it like this,if you want to print outside while loop,
String test ="";
String wfl ="";
while ((wfl = wbf.readLine()) != null) {
if(wfl.contains("A/C NO:")){
//System.out.println(wfl);//Here it is Printing the correct line
}
test = test + wfl ; // for assigning all line
//test = wfl // for assigning last line
}
System.out.println(test); // it wil print the correct line
The code below is mostly self explanatory. However, I am having trouble in two cases:
The while loop does not exit even with the command line is left blank.
If the input is test t1 the key variable is supposed to be "test" (using System.out.println(key)) does that, but, it still doesn't enter the if condition for some reason.
String[] broken_text = null; String text = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while((text = reader.readLine()) != null) {
broken_text = text.split(" ");
String first_key = broken_text[0];
if (first_key == "test") {
//some statements
}
}
I am not sure why this is happening, any help regarding the same will be much appreciated.
use equals() to check string equality.
if (first_key == "test") {
//some statements
}
should be
if (first_key.equals("test")) {
//some statements
}
your text will never be null because you declared it as
String text = "";
thus your while loop would be an infinite loop
change
String text = "";
to
String text = null;
or if you wanna leave your text="" string as empty string.
use
while(!(text = reader.readLine()).isEmpty())
The loop does not end because a blank line causes readLine() to return an empty string, not null.
The comparison fails because Strings must be compared with equals() not ==
The String text will never be null in this case. You can use:
while (!(text = reader.readLine()).isEmpty()) {
this should be your edited code:
String[] broken_text = null;
String text = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while((text = reader.readLine()) != null && !text.isEmpty()) {
broken_text = text.split(" ");
String first_key = broken_text[0];
if ( "test".equals(first_key)) {
//some statements
}
}
The reason changed (text = reader.readLine()) != null to (text = reader.readLine()) != null && !text.isEmpty() is because readLine() returns null when it encounters end-of-file as the first character, and it returns "" (empty string) when the first character is encounters is \r (carriage return), \n(line feed) , or \r\n(carriage return followed by line feed). And you must always check for null before checking for isEmpty().
On unix / Linux console end-of-file is [ctrl][d] and on DOS it is [ctrl][z]
Note: In case you want to read input from a file (where you are more likely to get an end-of-file) instead of console, then your reader will be initialised like this:
BufferedReader reader = new BufferedReader(new FileReader("d:\\a1.txt"));
(assuming your input data is in file: "d:\a1.txt".)