How to read CSV from 2nd Line in java? - java

I have a comma delimited CSV file ans I have the code to read it from 2nd line. But it gives me the following error.
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
This is my Code.
public static List<String> readCSV(String path){
BufferedReader br = null;
String[] cd = null;
String line ="";
String split=",";
List<String> list = new ArrayList<String>();
try {
br=new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
boolean firstLine = true;
while (line != null && line.startsWith("child's Last Name")) {
if (firstLine) {
firstLine = false;
continue;
} else {
list.add(line);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
How can I fix it with this code..
Thanks in Advance!

In your second while loop where are you assigning line again
while (line != null && line.startsWith("child's Last Name"))
Once this condition is satisfied, you are not reassigning it.
Your code should be different something like,
boolean firstLine = true;
while ((line = br.readLine()) != null)
{
if (firstLine)
{
firstLine = false;
continue;
}
else if(line != null && line.startsWith("child's Last Name"))
{
list.add(line);
}
}

try
br=new BufferedReader(new FileReader(path));
boolean firstLine = true;
while ((line = br.readLine()) != null) {
if (line.startsWith("child's Last Name")) {
if (firstLine) {
firstLine = false;
continue;
}
list.add(line);
}
}
There is no need for two while loops

Your problem has nothing to do with the 2nd line; You're simply trying to put the whole file in list and eventually, there's just too much to fit in memory. You have two choices:
Do not keep it all in memory! Process the line, do what you must, and don't store it, so it eventually gets garbage collected
If you really really must keep it all in memory, try increasing the amount of heap space available by starting java with a -Xmx parameter (run java -X for details)
UPDATE: oh oops, yes, as others said, you're also stuck in and endless loop. Consider this answer only once you've fixed that!

Usually, you get an out of memory error when you... well... run out of memory to run the application. Have you debugged into it? You could be stuck in an endless loop...
while (line != null && line.startsWith("child's Last Name")) {
Should this be an if statement?
EDIT:
while ((line = br.readLine()) != null) {
This really should be:
while(br.hasNext()) {
More info: Java - Read CSV with Scanner()

try this..
br=new BufferedReader(new FileReader(path));
br.readLine();
while ((line = br.readLine()) != null) {
if (line.startsWith("child's Last Name")) {
list.add(line);
}
}

Related

Exception in thread "main" java.lang.NumberFormatException: For input string: "" in Java

I created a class in java to read a text file (.txt) and print on the screen the result on the screen. Script is reading the contents of the text file, but at the end it is displaying the message:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at com.desafioProgramacao.LerArquivo.main(LerArquivo.java:24)
I do not know why it displays the message. In the FINALLY class I tell it to close the FileReader and the BufferedReader if the contents of the file are null. Follow the Java code and screen prints.
public class LerArquivo {
private static final String NomeArquivo = "E:\\DesafioProgramacao\\matriculasSemDV.txt";
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(NomeArquivo);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}}
The problem is the last line, it is a blank space. You can do:
while ((sCurrentLine = br.readLine()) != null) {
if (!sCurrentLine.isEmpty()) {
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
}
}
The cause on the surface is that your read an empty string and want to parse it to int
For the code,you need check the sCurrentLine value
while ((sCurrentLine = br.readLine()) != null) {
if(StringUtils.isNotBlank(sCurrentLine)){//StringUtils is from `commons-lang`
// or if(sCurrentLine.length()>0)
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
}
}
For the txt file,you need to remove all the empty line at the end of the file
Your file contains an empty line (probably at the end).
Replace your while loop with:
while ((sCurrentLine = br.readLine()) != null && !sCurrentLine.isEmpty())
The correct way to fix it is to catch that NumberFormatException and handle it properly, like that:
try {
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
} catch (NumberFormatException ex) {
System.out.println("Error reading line: " + sCurrentLine);
}

why Java buffered reader missed a lot of lines in output large txt file as input?

Hi I using following code
public class Readfiles {
FileInputStream fr;
public void readAll(){
try {
fr = new FileInputStream(new File("books/Artificial intelligence.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("File Not Found");
e.printStackTrace();
}
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
InputStreamReader reader = new InputStreamReader(fr, decoder);
BufferedReader br = new BufferedReader(reader);
try {
int i = 0;
for(String newLine; (newLine = br.readLine()) != null; )
{
newLine = br.readLine();
i++;
System.out.println(newLine);
}
br.close();
System.out.println(i);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
To read this txt file it is about 420.000 lines long:
Artificial intelligence.txt
But my code above dont read it correctly it is missing about half of the lines in the middle, and seems to start anywhere (each start randomly) the following is one of the possible result of the SYSOut :
Only first lines:
##Margaret H. Szymanski,Paul M. Aoki,Rebecca E. Grinter,Amy Hurst,James D. Thornton,Allison Woodruff
#cComputer Supported Cooperative Work
#%5488
#%87739
#%257074
#%818174
#!
#*Unpacking Tasks: The Fusion of New Technology with Instructional Work.
#t2008
#index831790
#%174882
#!
So the question is Why?
Printout of i is always 209647.
Well you are reading the line twice
once in
for(String newLine; (newLine = br.readLine()) != null; )
{
and then again in
newLine = br.readLine();
nicer would be
while ((newLine = br.readLine()) != null) {....}
You're calling br.readLine() twice in your loop, but only using the result of one of those two calls in your System.out.println call. So you're only printing out every second line.
You're calling br.readLine() twice
for(String newLine; (newLine = br.readLine()) != null; )
{
newLine = br.readLine();
i++;
System.out.println(newLine);
}
You can get rid of the one inside the loop
for(String newLine; (newLine = br.readLine()) != null; )
{
i++;
System.out.println(newLine);
}
for(String newLine; (newLine = br.readLine()) != null; )
{
i++;
System.out.println(newLine);
}

NullPointerException reading line from file [duplicate]

This question already has answers here:
Java if/else behaving strangely
(4 answers)
Closed 7 years ago.
I have this code:
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("hello.txt"));
String line;
while ((line = br.readLine().trim()) != null) {
if (line.startsWith("Hello")) {
line = br.readLine().trim();
} else {
... code ...
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But once the file reaches the end, I get this error:
Exception in thread "main" java.lang.NullPointerException
On the line:
while ((line = br.readLine().trim()) != null) {
Why? How to fix it?
Try the following; ine which you are trying to read is null hence calling trim throws NPE;
while (br.readLine() != null)
{
line = br.readLine().trim()
}
while ((line = br.readLine().trim()) != null)
remove the trim()
and added it within the while loop.
line = line.trim();
When you try to read using readLine()
line = br.readLine().trim())
if br.readLine() return null, then calling trim() cause NPE.
while ((line = br.readLine()) != null) {
line.trim();
if (line.startsWith("Hello")) {
if ((line = br.readLine()) != null) {
line.trim();
}
} else {
}
}

how to read last line in a text file using java [duplicate]

This question already has answers here:
Quickly read the last line of a text file?
(10 answers)
Closed 9 years ago.
I am making a log and I want to read the last line of the log.txt file, but I'm having trouble getting the BufferedReader to stop once the last line is read.
Here's my code:
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Here's a good solution. In your code, you could just create an auxiliary variable called lastLine and constantly reinitialize it to the current line like so:
String lastLine = "";
while ((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine);
lastLine = sCurrentLine;
}
This snippet should work for you:
BufferedReader input = new BufferedReader(new FileReader(fileName));
String last, line;
while ((line = input.readLine()) != null) {
last = line;
}
//do something with last!

Removing sentences containing a keyword in java

I am been searching online and on here on how I can remove a line that contains one or two words but I can't find anything on java. This is the code I have right now:
try {
BufferedReader reader = new BufferedReader(new FileReader("Readfile.txt"));
String line = reader.readLine();
while(line !=null)
{
for(int i = 0 ; i<newarray.length;i++){
if(line.contains(newarray[i])){
System.out.println(line);
}
}
line=reader.readLine();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
It reads sentences from a text file, but before it prints them out, I want to delete some sentences that contains a keyword, e.g. fun.
Something like this:
//BufferedReader stuff etc.
List<String> words = new ArrayList<String>();
words.add("fun");
words.add("something");
String line;
while( (line = br.readLine()) != null)
{
boolean found = false;
for(String word: words)
{
if(line.contains(word))
{
found = true;
break;
}
}
if(found) continue;
System.out.println(line);
}
if(line.contains(newarray[i])){
line = line.replace("fun" ,"");
System.out.println(line);
}
Try this it will delete the word before printing it.

Categories

Resources