Tokenizing issue with buffered reader - java

So I'm writing a java program that is supposed to keep analyzing strings from the user until the end of standard input (until they press CTRL+D or the end of an input file). The program works as intended, however when I press CTRL+D, there is a null pointer exception. Here is the code in question:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = " ";
while (line != null) {
line = in.readLine();
String[] tokens = line.split(" ");
System.out.println(line); ......
The null pointer is aimed at String[] tokens = line.split(" ");
It looks like the code is trying to tokenize a line that is null. But I thought I wrote it in a way to never attempt to tokenize a null line. Can anyone help me out?

Change your while loop to: -
while ((line = in.readLine())!= null) {
And remove the first line inside it.
Note that, you were reading the line inside the loop, and then testing later on. So, you would have got a NPE at the end of the file.
Also, if you are tokenizing the file after reading, I would prefer to use Scanner class indeed.

The problem is that while is a pre check condition. At the beginning of the loop, line isn't null. You should use a do-while instead.
while (line != null) {
line = in.readLine(); // in the loop, but in.readLine() returns null
String[] tokens = line.split(" "); // OH SHI- LINE IS NULL
System.out.println(line);

Related

Array is getting index out of bounds in one specific spot of text file

So I have a text file with very simple text. Each line is simply make,model,vin#. I have about 3 or 4 lines to test. When I print out these lines, only the lines with even indexes get printed. If I don't include the else statement then it gives an out of bounds exception. So for example, with text file input as shown
Hi guys. I have a text file that is only a few lines long. On each line, it is formatted as such:make,model,number. When I run my program, it prints the lines normally until it gets to the third line of the text file(there's only 5 lines). This third line is where I get the index out of bounds exception.
public CarDealershipSystem(File carFile, File associateFile) {
try (BufferedReader br = new BufferedReader(new FileReader(carFile))) {
String line;
for(;;) {
line = br.readLine();
String[] lineArray = line.split(",");
System.out.println(lineArray[0]);
System.out.println(lineArray[1]);
System.out.println(lineArray[2]);
}
}catch(IOException e) {
e.getLocalizedMessage();
e.printStackTrace();
}
You have "line = br.readLine()" in two places in "while" cycle and in "if" block that causes two calls to readLine per cycle. Besides this block is pointless because the "while" condition already handles it.
tldr: remove
if((line = br.readLine()) == null) {
break;
}
you need a break when you reach the end of the file.
String line;
while((line = br.readLine()) != null) { //stop loop when line == null
line = br.readLine();
}
you need to check your input, before split
String[] lineArray = line.split(",");
if (lineArray != null && lineArray.length == 3) { //will help you avoid the ArrayIndexOutOfBoundsException exception
System.out.println(lineArray[0]);
System.out.println(lineArray[1]);
System.out.println(lineArray[2]);
}

Ignore new lines while reading a file

I'm trying to read text inside a .txt document using console command java program < doc.txt. The program should look for words inside a file, and the file CAN contain empty new lines, so I've tried changing the while condition from:
while((s = in.nextLine()) != null)
to:
while((s = in.nextLine()) != "-1")
making it stop when it would have found -1 (I've also tried with .equals()), but it does not work. How can I tell my program to stop searching for words when there's no more text to examine? Otherwise it keeps stopping when it finds an empty string (newline alone or sequence of new lines).
I've only found solutions using BufferedReader, but I don't know how to use it in this situation where the file is being read by the console command java program < doc.txt.
I post the code inside the while, if it can be necessary:
while((s = in.nextLine()) != null) {
s = s.toLowerCase();
Scanner line = new Scanner(s);
a = line.next();
if(a.equals("word")) {
k++;
}
}
Proper way of figuring out when Scanner runs out of input is checking hasNextLine() condition. Use this loop to read a sequence of strings that includes empty lines:
Scanner in = new Scanner(System.in);
while(in.hasNextLine()) {
String s = in.nextLine();
System.out.println(s);
}
Demo.

Reading a file and performing functions based on the contents of the line

I'm wondering if it's possible to read a file by the line number, each with different values and make a condition where if that line contains a certain string or number specified. If it did it would, for example, take the content specified in that line into a variable?
So in a file line one has Age: 50, line 2 has Age: 23, line 3 has Age: 34. What I'm hoping for is that I look specifically at line 3 and take the number 34 and place it in a variable for use in my program.
If it is possible, how would you go about doing this?
I would say, it is not possible to directly address a specific line unless - perhaps you know the line sizes of your file, etc... to seek through the file. But you can use this to go through your file, line by line:
String line;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
// do some cool stuff with this line.
}
br.close();
Possible duplicate: Reading a file and performing functions based on the contents of the line
You can always iterate through each line, keeping track of the line via an int or a short.
some code:
String line;
BufferedReader br = new BufferedReader(new FileReader(FILE_HERE));
int line = 0;
while ((line = br.readLine()) != null) {
line++;
if(line == 3){
//do whatever you want
}
}
br.close();
I will add that getting something from one single line while others also have identical info is bad
you can use the scanner object to read through a file. you would use the delimiter to find the info you want and a counter to keep track of the line, then put it in an arraylist or something. depending on what you want to do.
Scanner in = new Scanner(filename);
int line = 0;
in.useDelimiter("[regex of the info you are looking for]");
while in.hasNext()) {
line++
//do something
}

NullPointerException when trying to read a file line by line (Java)?

I'm trying to read a file line by line, but every time I run my program I get a NullPointerException at the line spaceIndex = line.indexOf(" "); which obviously means that line is null. HOWEVER. I know for a fact that the file I'm using has exactly 7 lines (even if I print the value of numLines, I get the value 7. And yet I still get a nullpointerexception when I try to read a line into my string.
// File file = some File I take in after clicking a JButton
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(file.toPath(), charset)) {
String line = "";
int spaceIndex;
int numLines = 0;
while(reader.readLine()!=null) numLines++;
for(int i = 0; i<numLines; i++) {
line = reader.readLine();
spaceIndex = line.indexOf(" ");
System.out.println(spaceIndex);
}
PS: (I'm not actually using this code to print the index of the space, I replaced the code in my loop since there's a lot of it and it would make it longer to read)
If i'm going about reading the lines the wrong way, it would be great if someone could suggest another way, since so far every way I've tried gives me the same exception. Thanks.
By the time you start your for loop, the reader is already at the end of the file
(from the while loop).
Therefore, readLine() will always return null.
You should get rid of the for loop and do all of your work in the while loop as you first read the file.
You have two options.
First, you could read number of lines from a file this way:
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("File1")));
lnr.skip(Long.MAX_VALUE);
System.out.println(lnr.getLineNumber());
Then read the file right after:
while((line = reader.readLine())!=null)
{
spaceIndex = line.indexOf(" ");
System.out.println(spaceIndex);
}
This first option is an alternative (and in my my opinion, cooler) way of doing this.
Second option (and probably the more sensible) is to do it all at once in the while loop:
while((line = reader.readLine())!=null)
{
numLines++;
spaceIndex = line.indexOf(" ");
System.out.println(spaceIndex);
}

Reading lines from text files in Java

I am trying to read product information from some text files. In my text file I have products and their information.
This is my file:
Product1:
ID: 1232
Name: ABC35
InStock: Yes
As you see, some products have blank lines in their product information, and I was wondering if there is any good way to determine if the line is blank, then read the next line.
How can I accomplish that? If the reading line is blank, then read the next line.
Thanks in advance for any help.
I think I may be misunderstanding. Assuming you have a BufferedReader, your main processing loop would be:
br = /* ...get the `BufferedReader`... */;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() == 0) {
continue;
}
// Process the non-blank lines from the input here
}
Update: Re your comment:
For example if I want to read the line after name, if that line is blank or empty, I want to read the line after that.
The above is how I would structure my processing loop, but if you prefer, you can simply use a function that returns the next non-blank line:
String readNonBlankLine(BufferedReader br) {
String line;
while ((line = br.readLine()) != null) {
if (line.trim().length() == 0) {
break;
}
}
return line;
}
That returns null at EOF like readLine does, or returns the next line that doesn't consist entirely of whitespace. Note that it doesn't strip whitespace from the line (my processing loop above does, because usually when I'm doing this, I want the whitespace trimmed off lines even if they're not blank).
Simply loop over all the lines in the file, and if one is blank, ignore it.
To test if it's blank, just compare it to the empty String:
if (line.equals(""))
This won't work with lines with spacing characters (space, tabs), though. So you might want to do
if (line.trim().equals(""))
Try checking the length of the line:
String line;
while((line= bufreader.readLine()) != null)
if (line.trim().length() != 0)
return line;

Categories

Resources