【问题标题】:How to load a UTF-8 text file with InputStream如何使用 InputStream 加载 UTF-8 文本文件
【发布时间】:2015-02-08 12:32:19
【问题描述】:

我想通过按下按钮将我的资产文件夹中的 .txt 文件加载到文本视图中。我这样做了,但我的问题是我的文本文件是 UTF-8 编码文本,一些奇怪的字符被复制到我的 TextView 中,而不是我的真实单词...... 这是我编写的代码和方法,但我不知道应该将“UTF-8”作为参数放在哪里..

b1.setOnClickListener(new View.OnClickListener() {          
        @Override
        public void onClick(View arg0) {                
            try {
                InputStream iFile = getAssets().open("mytext.txt");
                String strFile = inputStreamToString(iFile);
                Intent intent=new Intent(MyActivity.this,SecondActivity.class);
                   intent.putExtra("myExtra", strFile);
                final int result=1;
                   startActivityForResult(intent, result);
            } catch (IOException e) {                   
                e.printStackTrace();
            }

public String inputStreamToString(InputStream is) throws IOException {
    StringBuffer sBuffer = new StringBuffer();
    DataInputStream dataIO = new DataInputStream(is);
    String strLine = null;
    while ((strLine = dataIO.readLine()) != null) {
        sBuffer.append(strLine + "\n");
    }
    dataIO.close();
    is.close();
    return sBuffer.toString();
}

感谢您的帮助 ;-)

【问题讨论】:

  • 1 - 将 UTF-8 定义放入 xml 布局中。 2 - 使用具有该特定语言的所有字形的 font3 - 将文本文件保存为 Unicode UTF-8 编码(Android 端不会翻译)。即don't use Windows Notepad保存文件。
  • 尝试在 open() 或 new() 中添加一个额外的参数。
  • InputStreamReader 对字符集有重载,请使用该字符集而不是常规的 StringBuffer

标签: java android utf-8 io inputstream


【解决方案1】:

以下代码将您的文件读入字节数组缓冲区并将其转换为字符串

public String inputStreamToString(InputStream is) throws IOException {
    byte[] buffer = new byte[is.available()];
    int bytesRead = is.read(buffer);
    return new String(buffer, 0, bytesRead, "UTF-8");
}

【讨论】:

    猜你喜欢
    • 2014-12-17
    • 2012-07-21
    • 2015-08-13
    • 1970-01-01
    • 2023-04-01
    • 2016-01-05
    • 2018-05-17
    相关资源
    最近更新 更多