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;
Related
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]);
}
Hi I was looking to get some help with skipping null lines, I've searched for answers but im not able to find any. This is the code I'm trying to use:
BufferedReader in = new BufferedReader(new FileReader(newest));
String line = "";
while (true) {
if ((line = in.readLine()) == null) {
I would expect the code to look something like this:
String line;
while ((line=in.readLine())!=null) {
if (!line.isEmpty()) {
// do stuff
}
}
Normally I'd trim each line before checking if it is empty, but you say you want to exclude "a line that is blank and has no spaces", which implies you want to include lines that are just space.
If you do want to skip lines that are all whitespace, you could do this:
String line;
while ((line=in.readLine())!=null) {
if (!line.trim().isEmpty()) {
// do stuff
}
}
The point of the while condition is that the BufferedReader will return null when the input is finished, so that should trigger the end of the loop.
Lines won't be null, they may just be empty. What I would do is check if it is empty:
if ((line = in.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
}
}
While reading from this stream, null will only be encountered at the end of the stream (file in this case). If you're looking for an empty/blank string, that test is within the loop (below).
Note that String.trim() does not trim the object itself, it returns the trimmed String. Equals method should generally be used to test for Object (such as String) equality.
BufferedReader in = new BufferedReader(new FileReader(newest));
String line = "";
//Line below keeps looping while the reader return a valid line of text.
//If the end of stream (file in this case) has been reached, you'll get null.
while ((line=in.readLine())!=null) {
//line below tests for empty line
if(line.trim().equals(""){
}
}
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
}
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);
I'm writing this code to look inside a txt file and find me a string that the user gave as input. My txt file contains the lines as such (this info will be important later):
first line - blank.
second line - idan
third line - yosi
now, if the user inputs "idan" as the user (without the "") the code will find it. If the user puts in "yosi" it wont find it. It's like my code is reading only the second line. I'm new in programming and this is just a practice for me to learn how to read and write to files, please be patient with me.
here is the code (there is a catch and also the else statement but they where left off for length reasons):
//Search for the specific profile inside.
try{
BufferedReader br = new BufferedReader(new FileReader("d:\\profile.txt"));
System.out.println("Searching for your Profile...");
int linecount = 0;
String line;
while (br.readLine() !=null){
linecount++;
if(userName.contentEquals(br.readLine())){
System.out.println("Found, " + userName + " profile!");
break;
}
else{
}
The problem is this:
*if(userName.contentEquals(br.readLine())){*
you are reading an additional line. You will find it reads every other line with your implementation. That is line 2,4,6,etc
The problem is in the following place:
if(userName.contentEquals(br.readLine()))
You don't need to read it again because you have already read it in the while loop:
while (br.readLine() !=null)
So, you basically read line1 (do nothing with it), then read line2 (do something with it) and the process starts over.
You want to do something like
...
String line;
while((line = br.readLine()) != null) {
...
}
Every call to BufferedReader.readLine() reads the next available line from the file. Since you read one line in the while statement and read the next line for the if statement, you're only checking the even numbered lines.