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
Related
BufferedReader br = new BufferedReader(new FileReader(fileLocation));
String contentLine = br.readLine();
while(contentLine!= null){
System.out.println(contentLine);
contentLine = br.readLine();
}
return contentLine; // returns null
}
Hello All,
I am in process of learning java, and here i am trying to parse a file that prints out the json message, the challenge I am facing is, I need to return that json which is inside while loop. Currently, the method returns null
To cement the comments above, use a different variable and then append to the returned value
BufferedReader br = new BufferedReader(new FileReader(fileLocation));
StringBuilder contentLine = new StringBuilder ();
while(true){
String tmp = br.readLine();
if (tmp == NULL) {
break;
}
contentLine.append (tmp);
System.out.println(contentLine.toString ());
}
return contentLine.toString ();
I am taking data from a text file and putting it into an ArrayList. However the first line of the text file is not being printed out.
public static void secondMain() {
BufferedReader reader;
var lines = new ArrayList<String>();
var rooms = new ArrayList<Room>();
try {
reader = new BufferedReader(new FileReader("rooms.txt"));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
lines.add(line);
}
reader.close();
for (int i = 0; i < lines.size() - 1; i++) {
String[] words = lines.get(i).split(" ");
var room = new Room();
room.RoomNumber = Integer.parseInt(words[0]);
room.Type = (words[1]);
room.Price = Double.parseDouble(words[2]);
room.Bool1 = Boolean.parseBoolean(words[3]);
room.Bool2 = Boolean.parseBoolean(words[4]);
room.Availability = (words[5]);
rooms.add(room);
}
for(int i = 0; i < rooms.size(); i++) {
System.out.println(rooms.get(i).RoomNumber);
System.out.println(rooms.get(i).Type);
System.out.println(rooms.get(i).Price);
System.out.println(rooms.get(i).Bool1);
System.out.println(rooms.get(i).Bool2);
System.out.println(rooms.get(i).Availability);
}
Apologies for the Image, it was the only way i could figure out how to show the formatting of the text file.
The current output is displaying room number 102 as the first room which obviously isn't correct.
If anyone could also help me figure out how to format my console output the same way as the text file that'd also be great. currently it is displaying each individual string/int etc. on a different line.
Thanks.
If you need any more information please just ask!
This has nothing to do with the ArrayList. You can reproduce the problem by replacing the lines.add(line) call with System.out.println(line) and you'll see that the first line is missing from the output. Look at your first call to readLine(), before the while loop. You test that the value is non-null... and that's all you do with it (comments mine):
String line = reader.readLine(); // Read the value...
while (line != null) { // Test for it being non-null
line = reader.readLine(); // Then ignore the value you've just tested,
// by reading the next line.
lines.add(line);
}
You then call readLine() again. Note that your list will always end with a null value (unless it's the first line read) because your loop effectively says "while the last entry I added to the list isn't null". The simplest fix is to swap the order of the statements within your loop:
String line = reader.readLine();
while (line != null) {
lines.add(line);
line = reader.readLine();
}
Now you're adding a line immediately after checking whether it's non-null, before reading the next line.
The problem is here:
String line = reader.readLine(); // you read the first line
while (line != null) {
line = reader.readLine(); // read second line
lines.add(line); // add second line
}
You read the first line, check if it's not null, and then read the second line right away, before you add it to the list. All you need to do is switch the order.
String line = reader.readLine();
while (line != null) {
lines.add(line);
line = reader.readLine();
}
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.
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
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".)