6

代码:

public class MainApplication {

      public static void main(String[] args) throws IOException {

              try{
                  // Open the file that is the first 
                  // command line parameter
                  FileInputStream fstream = new FileInputStream("data/temp.CSV");
                  BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
                  String strLine;
                  //Read File Line By Line
                  while ((strLine = br.readLine()) != null)   {
                  // Print the content on the console
                  System.out.println (strLine);
                  }
                  //Close the input stream
                  in.close();
                    }catch (Exception e){//Catch exception if any
                  System.err.println("Error: " + e.getMessage());
                  }
      }
}

CSV 文件数据:

19/1/13 13:58:04    0   1610    0   419 0   0
19/1/13 13:58:05    0.01    1599    66  432 0   1
19/1/13 13:58:06    0.02    1603    47  423 0   2
19/1/13 13:58:07    0.03    1602    26  413 0   3
19/1/13 13:58:08    0.04    1605    130 412 0   4

输出:

错误画面

4

2 回答 2

4

利用

BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-16LE"));

代替

BufferedReader br = new BufferedReader(new InputStreamReader(in));
于 2013-01-29T17:28:40.310 回答
4

代替

BufferedReader br = new BufferedReader(new InputStreamReader(in));

BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

替换"UTF-8"为文件的编码.csv

InputStreamReader根据给定的字符集,使用此构造函数处理您的输入正确。如果您没有指定字符集并且有奇怪的输出,则表明文件以不同于系统默认编码的编码进行编码。

此外,你可以摆脱DataInputStream和写

BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF-16"));

编辑 感谢亨利指出以下几点:

查看您的输出,每个字符似乎都使用 2 个字节进行编码。这表明它的编码是 UTF-16。您应该"UTF-16"相应地在构造函数中使用。

于 2013-01-29T17:18:52.923 回答