Java打印正方形(未知字符)以及常规文本

时间:2013-01-29 17:15:35

标签: java file csv

代码:

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

输出:

Error screen

2 个答案:

答案 0 :(得分: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"));

编辑 感谢Henry指出以下内容:

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

答案 1 :(得分:2)

使用

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

而不是

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