【问题标题】:Read content from txt file to string including special characters将 txt 文件中的内容读取到包含特殊字符的字符串
【发布时间】:2015-10-20 04:52:11
【问题描述】:

我想从文件中读取文本并将其存储在字符串中。但我无法获得相同的内容。我正在使用下面的代码

String content = readFile(filepath, StandardCharsets.UTF_8);

String readFile(String path, Charset encoding) 
        throws IOException 
    {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }

我的文本文件包含 Máquina blah blah , blah İletişim ve blah A.Ş. 但是当我使用 UTF-8 编码时,我会得到这样的输出 M??quina blah blahblah ??leti??im ve blah A.??.

请帮助我使用适当的编码功能来阅读我的文本。提前致谢

【问题讨论】:

  • 你在使用 Eclipse 吗?
  • 是的。我只使用 Eclipse

标签: java encode


【解决方案1】:

如果您使用的是 Eclipse,我之前已经看到过这个问题。 它是不支持您尝试打印的字符的输出控制台。您需要确保将 Eclipse 安装配置为使用 UTF-8。

为此,

Window => Preferences => General => Workspace => Text File Encoding => 设置为 UTF-8。

【讨论】:

    【解决方案2】:

    这段代码对我有用..谢谢:)

            StringBuilder sb = new StringBuilder();
            BufferedReader bufRdr  = new BufferedReader(new InputStreamReader(new FileInputStream(fileObj),"UTF-8"));
            String line = null;
    
            line = bufRdr.readLine();
              while (line != null) {
                    sb.append(line);
                    sb.append("\n");
                    line = bufRdr.readLine();
                }
    

    【讨论】:

      猜你喜欢
      • 2020-12-25
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多