How to skip null lines in java? - java

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(""){
}
}

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]);
}

How do I use BufferedReader to read lines from a txt file into an array

I know how to read in lines with Scanner, but how do I use a BufferedReader? I want to be able to read lines into an array. I am able to use the hasNext() function with a Scanner but not a BufferedReader, that is the only thing I don't know how to do. How do I check when the end of the file text has been reached?
BufferedReader reader = new BufferedReader(new FileReader("weblog.txt"));
String[] fileRead = new String[2990];
int count = 0;
while (fileRead[count] != null) {
fileRead[count] = reader.readLine();
count++;
}
readLine() returns null after reaching EOF.
Just
do {
fileRead[count] = reader.readLine();
count++;
} while (fileRead[count-1]) != null);
Of course this piece of code is not the recommended way of reading the file, but shows how it might be done if you want to do it exactly the way you attempted to ( some predefined size array, counter etc. )
The documentation states that readLine() returns null if the end of the stream is reached.
The usual idiom is to update the variable that holds the current line in the while condition and check if it's not null:
String currentLine;
while((currentLine = reader.readLine()) != null) {
//do something with line
}
As an aside, you might not know in advance the number of lines you will read, so I suggest you use a list instead of an array.
If you plan to read all the file's content, you can use Files.readAllLines instead:
//or whatever the file is encoded with
List<String> list = Files.readAllLines(Paths.get("weblog.txt"), StandardCharsets.UTF_8);
using readLine(), try-with-resources and Vector
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\weblog.txt")))
{
String line;
Vector<String> fileRead = new Vector<String>();
while ((line = bufferedReader.readLine()) != null) {
fileRead.add(line);
}
} catch (IOException exception) {
exception.printStackTrace();
}

BufferedReader to read lines, then assign the new formed line's tokens to variables

I have a text file that I need to modify before parsing it. 1) I need to combine lines if leading line ends with "\" and delete white spaced line. this has been done using this code
public List<String> OpenFile() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
StringBuilder concatenatedLine = new StringBuilder();
List<String> formattedStrings = new ArrayList<>();
while ((line = br.readLine()) != null) {
if (line.isEmpty()) {
line = line.trim();
} else if (line.charAt(line.length() - 1) == '\\') {
line = line.substring(0, line.length() - 1);
concatenatedLine.append(line);
} else {
concatenatedLine.append(line);
formattedStrings.add(concatenatedLine.toString());
concatenatedLine.setLength(0);
}
}
return formattedStrings;
}
}
}//The formattedStrings arrayList contains all of the strings formatted for use.
Now My question, how can I search those lines for pattern and assign their token[i] to variables that I can call or use later.
the New combined text will look like this:
Field-1 Field-2 Field-3 Field-4 Field-5 Field-6 Field-7
Now, if the line contains "Field-6" and "Field-2" Then set the following:
String S =token[1] token[3];
String Y =token[5-7];
Question you might have for me, how am I deciding on which token to save to a string? I will manually search for the pattern in the text file and if the "Line contain Field-6 and Field-2 or any other required pattern. Then manually count which token I need to assign to the string. However, it will be nice if there is another way to approach this, for ex assign what's in between token[4] and token[7] to string (s) if the line has token[2] and token[6]. or another way that provides more Granule Control over what to store as string and what to ignore.

Assigning values in the predicate of a while loop - BufferedReader

I have a piece of code that looks like this:
public void cinemaFromFile(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
if (line.equals("Movies")) {
while ((line = reader.readLine()) != null
&& !line.equals("Theaters")) {
String currentline = line;
String[] parts = currentline.split(":");
String part1 = parts[0];
String part2 = parts[1];
movies.add(new Movie(part1, part2));
}
}
reader.close();
}
As you can see, I assign line a value in the termination clause of the while loop.
I am new to BufferedReaders and I am looking for an alternative to this. IE, I want to have the assignment statement("line = reader.readLine()") in a separate statement, external to the while loop termination clause.
I have tried moving "line = reader.readLine()" into the body of the while loop but that doesn't work. I have also tried putting it right before the while loop, which also doesn't work.
I think I have fundamentally misunderstood how BufferedReaders work, can they only iterate through the lines in while loops?
To pull the assignment out of the while loop condition, you must understand that the while loop condition is evaluated once before the first iteration, and after the end of each iteration.
You can emulate that by placing the assignment before the while loop even begins, and also adding it to the end of the while loop body.
line = reader.readLine();
while (line != null) {
// Rest of body is untouched
// Read again at the end.
line = reader.readLine();
}
This will operate the same. It may even be a little clearer than having the assignment in the condition of the while loop, even if it's a little less concise.
The BufferedReader does nothing special in this regard with while loops. It just returns null when readLine() is called and there's no input left.
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while (true) {
line = reader.readLine();
if(line == null)
break;
if (line.equals("Movies")) {

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