簡體   English   中英

如何使用InputStream加載UTF-8文本文件

[英]How to load a UTF-8 text file with InputStream

我想通過按下按鈕將資產文件夾中的.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();
}

謝謝你的幫助 ;-)

以下代碼將文件讀入字節數組緩沖區,並將其轉換為字符串

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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM