简体   繁体   中英

Reading CSV file in java adds space between each character

I'm reading a CSV file downloaded form google trend, here are the contents of file when opened in notepad (first two lines only):

ferrari ferrari (std error)
0.735 2%

When I read the file using readline the line read contains space between each character, in above case the output is:

ferrariferrari ( stderror )
0 . 7 3 5 2 %

(There are tabs between "ferrari" and "ferrari" and between 0.735 and 2% which stackoverflow is not showing)

Newline character at end of each line is also read two times. Why is it that? Any solution?

Here is the code I'm using to read the file:

BufferedReader Reader = new BufferedReader(new FileReader("trend.csv"));
String line = null;
while ((line = Reader.readLine()) != null)
    System.out.println(line);

Edit: there are also some strange characters read at the starting of file

Edut: Got the solution

It was the encoding problem, changed the first line to:

BufferedReader Reader = new BufferedReader(new InputStreamReader(new FileInputStream("trend.csv"), "UTF-16"));

It is due to the character encoding... I've just downloaded the file from trends and tried, it had the same problem.

I got around with this if I use UTF-16 character set.

public class TrendReader
{
    public static void main(String args[]) throws Exception
    {
        //BufferedReader Reader = new BufferedReader(new FileReader("trends.csv"));
        BufferedReader Reader = new BufferedReader(new InputStreamReader(new FileInputStream("trends.csv"), "UTF-16"));
        String line = null;
        while ((line = Reader.readLine()) != null)
        {
            System.out.println(line);
        }
    }
}

You need to check the encoding of the file and based on that you should specify it while reading the file:

BufferedReader Reader = new BufferedReader(new InputStreamReader(new 
FileInputStream("trends.csv"), "UTF-8"));

If you expect the file in UTF-8 then change the encoding of the file, instead of your code, it's pretty simple you can use any open source CSV reader like OpenOffice to read this file and while opening specify the encoding :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM