dave4422
dave4422

Reputation: 3

code creates different different results Reading csv file and txt file - java

BufferedReader reader = new BufferedReader(in);
try {

  String line = reader.readLine();
  while (line != null) {

    result.append(line);
    line = reader.readLine();
    if (line != null) {
      result.append("\n");
    }
  }
}

Hello, I want to read a csv file and save each line into an array but my code reads an empty line after each text line. If I save the csv as txt and try the same code it works. -.- You find the csv file here https://www.dropbox.com/s/3wgl24tikm5xj6f/2408201406022015.csv?dl=0

What am I doing wrong?

Upvotes: 0

Views: 153

Answers (1)

Michael Krause
Michael Krause

Reputation: 4849

From the Javadoc for BufferedReader:

A line is represented by zero or more characters followed by '\n', '\r', "\r\n" or the end of the reader

When I look at the csv file you specified in a hex editor, I see \n\r pairs which is weird. Normally, you'd see the lines terminated with \r\n.

That explains why the Reader is interpreting things with an extra empty line.

Use the String.trim() method to trim leading and trailing whitespace and then check the length of the resulting String to see whether or not to append it to your StringBuilder.

Also, be sure to close your BufferedReader in a finally block when you're done with it.

Something like:

StringBuilder result = new StringBuilder();

BufferedReader reader = null;

try {
    reader = new BufferedReader(in);

    String line;

    while ((line = reader.readLine()) != null) {
        line = line.trim();
        if (line.length() > 0) {
            result.append(line);
            result.append('\n');
        }
    }
} catch (IOException e) {

}
finally {
    if (reader != null) {
        try {reader.close();} catch (IOException e) {}
    }
}

System.out.println(result.toString());

Upvotes: 3

Related Questions