How to Check for empty line while parsing csv file? - java

From third party daily reports i will be getting a similar kind of csv file as shown below
07-Jan-2016
It is better to lead from behind and to put others in front, especially when you celebrate victory when nice things occur. You take the front line when there is danger. Then people will appreciate your leadership.
The main thing that you have to remember on this journey is, just be nice to everyone and always smile.
My requirement is that i need to put each paragraph (A line after space) each quote for above reference in a separate StringBuffer
My question how can i check for empty line ??
I tried with
if(line.contains(" "))
{
System.out.println("hjjjjjjjjjjjjjjjjk");
}
But the above is causing issue where ever there is a space
I am reading the csv file as shown below
String csvFile = "ip/ASRER070116.csv";
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.startsWith(",")) {
line = line.replaceFirst(",", "");
}
System.out.println(line);
}
}
Could you please tell me how to resolve this ??

if (line != null && (line.trim().equals("") || line.trim().equals("\n"))){
System.out.println("this is empty line");
}

I would suggest you use trim() on the read line and then check if line.length == 0

You can use StringUtils.isBlank method from Apache Commons Lang
public static boolean isBlank(CharSequence cs)
Checks if a CharSequence is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false

Related

How to make sure when I am reading a bufferedReader the line is not empty?

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

Count number of lines in text skipping the empty ones

I need help with this. Can you tell me how to calculate the number of lines in the input.txt without counting the empty space lines?
So far, I tried:
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
int lines = 0;
while (reader.readLine() != null)
lines++;
So, this code is able to count the number of lines, but with the empty lines! I know that there are characters /n which illustrates the new line but I do not know how to integrate it in the solution.
I also tried to calculate number of lines, number of empty lines and subtract them, but I wasn't successful.
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
int lines = 0;
String line;
while ((line = reader.readLine()) != null){
if(!"".equals(line.trim())){
lines++;
}
}
You just need to remember the line you're looking at, and check it before counting:
int lines = 0;
String line;
while ((line = reader.readLine()) != null) {
if (!line.isEmpty()) {
lines++;
}
}
Note that you should be closing your reader too - either in an explicit finally statement, or using a try-with-resources statement in Java 7. I'd advise not using FileReader, too - it always uses the platform default encoding, which isn't a good idea, IMO. Use FileInputStream with an InputStreamReader, and state the encoding explicitly.
You might also want to skip lines which consist entirely of whitespace, but that's an easy change to make to the if (!line.isEmpty()) condition. For example, you could use:
if (!line.trim().isEmpty())
instead... although it would be cleaner to find a helper method which just detected whether a string only consisted of whitespace rather than constructing a new string. A regex could do this, for example.
BufferedReader's readLine() method only returns null when the end of the stream has been reached. To not count empty lines, test if the line exists and if it's empty then don't count it.
Quoting the linked Javadocs above:
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
Clean and fast.
try (BufferedReader reader = new BufferedReader("Your inputStream or FileReader")) {
nbLignes = (int) reader.lines().filter(line -> !line.isEmpty()).count();
}

Using readline() and split()

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".)

no line found exception

Help again guys, why do I always get this kind of error when using scanner, even though I'm sure that the file exists.
java.util.NoSuchElementException: No line found
I am trying to count the number of occurences of a by using for loop. the text file contain lines of sentence. At the same time, I want to print the exact format of sentences.
Scanner scanLine = new Scanner(new FileReader("C:/input.txt"));
while (scanLine.nextLine() != null) {
String textInput = scanLine.nextLine();
char[] stringArray = textInput.toCharArray();
for (char c : stringArray) {
switch (c) {
case 'a':
default:
break;
}
}
}
while(scanLine.nextLine() != null) {
String textInput = scanLine.nextLine();
}
I'd say the problem is here:
In your while condition, you scan the last line and come to EOF. After that, you enter loop body and try to get next line, but you've already read the file to its end. Either change the loop condition to scanLine.hasNextLine() or try another approach of reading files.
Another way of reading the txt file can be like this:
BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(new File("text.txt")))));
String line = null;
while ((line = reader.readLine()) != null) {
// do something with your read line
}
reader.close();
or this:
byte[] bytes = Files.readAllBytes(Paths.get("text.txt"));
String text = new String(bytes, StandardCharsets.UTF_8);
You should use : scanner.hasNextLine() instead of scanner.nextLine() in the while condition
Scanner implements the Iterator interface which works by this pattern:
See if there is a next item (hasNext())
Retrieve the next item (next())
To count the number of occurrences of "a" or for that matter any string in a string, you can use StringUtils from apache-commons-lang like:
System.out.println(StringUtils.countMatches(textInput,"a"));
I think it will be more efficient than converting the string to character array and then looping over the whole array to find the number of occurrences of "a". Moreover, StringUtils methods are null safe

How to skip certain line from Text file in java?

I am currently learning Java and I have faced this problem where I want to load a file that consists a huge number of lines (I am reading the file line by line ) and the thing I want to do is skip certain lines (pseudo-code).
the line thats starts with (specific word such as "ABC")
I have tried to use
if(line.startwith("abc"))
But that didn't work. I am not sure if I am doing it wrong, that's why I am here asking for a help, below part of the load function:
public String loadfile(.........){
//here goes the variables
try {
File data= new File(dataFile);
if (data.exists()) {
br = new BufferedReader(new FileReader(dataFile));
while ((thisLine = br.readLine()) != null) {
if (thisLine.length() > 0) {
tmpLine = thisLine.toString();
tmpLine2 = tmpLine.split(......);
[...]
Try
if (line.toUpperCase().startsWith(­"ABC")){
//skip line
} else {
//do something
}
This will converts the line to all the Upper Characters by using function toUpperCase() and will check whether the string starts with ABC .
And if it is true then it will do nothing(skip the line) and go into the else part.
You can also use startsWithIgnoreCase which is a function provided by the Apache Commons . It takes the two string arguments.
public static boolean startsWithIgnoreCase(String str,
String prefix)
This function return boolean.
And checks whether a String starts with a specified prefix.
It return true if the String starts with the prefix , case insensitive.
If the case isn't important try using the StringUtils.startsWithIgnoreCase(String str,
String prefix) of Apache Commons
This function return boolean.
See javadoc here
Usage:
if (StringUtils.startsWithIgnoreCase(­line, "abc")){
//skip line
} else {
//do something
}
If you have large a input File, you code will create a OutOfMemoryError. there is nothing you can do against it without editing te code (adding more memory will fail, if the file gets bigger).
I beleave you store the selected lines in memory. If the file gets lager (2GB or so) you'll have 4GB in memory. (The old Value of the String and the new one).
You have to work with streams to solve this.
Create a FileOutpuStream, and write the selcted line into that Stream.
Your method must be changed. For a large input yo cannot return a String:
public String loadfile(...){
You can return a Stream or a file.
public MyDeletingLineBufferedReader loadFile(...)
you can use:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String lineString;
try{
while((lineString = br.readLine()) != null) {
if (lineString.toUpperCase().startsWith(­"abc")){
//skip
} else {
//do something
}
}
}
or
static boolean startsWithIgnoreCase(String str, String prefix) method in org.apache.commons.lang.StringUtils like below.
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String lineString;
try{
while((lineString = br.readLine()) != null) {
if (StringUtils.startsWithIgnoreCase(­lineString, "abc")){
//skip
} else {
//do something
}
}
}

Categories