Android中讀取中文字元的檔案與檔案讀取相關

來源:互聯網
上載者:User

一、如何顯示assets/license.txt(中文)的內容?

(1)方法1:InputStream.available()得到位元組數,然後一次讀取完。

private String readUserAgreementFromAsset(String assetName) {

         String content ="";

         try {

                   InputStream is= getAssets().open(assetName);

                   if (is != null){

                            DataInputStream dIs = newDataInputStream(is);

                            intlength = dIs.available();

                            byte[] buffer = new byte[length];

                            dIs.read(buffer);

                            content= EncodingUtils.getString(buffer, "UTF-8");

                            is.close();

                   }

         } catch (IOException e) {

                   e.printStackTrace();

         }

         return content;

}

(2)方法2:用BufferedReader.readLine()行讀取再加分行符號,最後用StringBuilder.append()串連成字串。

A.以下是先行讀取再轉碼UTF8:

private String readUserAgreementFromAsset(String assetName) {

         StringBuilder sb = newStringBuilder("");

         String content ="";

         try {

                   InputStream is= getAssets().open(assetName);

                   if (is != null){

                            BufferedReader d = newBufferedReader(new InputStreamReader(is));

                            while (d.ready()) {

                                      sb.append(d.readLine() +"\n");

                            }

                            content =EncodingUtils.getString(sb.toString().getBytes(), "UTF-8");

                            is.close();

                  }

         } catch (IOException e) {

                  e.printStackTrace();

         }

         return content;

}

B.以下是InputStreamReader先指定以UTF8讀取檔案,再進行讀取讀取操作:

private String readUserAgreementFromAsset(String assetName) {

         StringBuilder sb = newStringBuilder("");

         String content ="";

         try {

                   InputStream is= getAssets().open(assetName);

                   if (is != null){

                            BufferedReaderd = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                            while(d.ready()) {

                                     sb.append(d.readLine() +"\n");

                            }

                            content= sb.toString();

                            is.close();

                   }

         } catch (IOException e) {

                  e.printStackTrace();

         }

         return content;

}

另外,UTF8轉碼也可以用new String(buffer, “utf-8”)。

(3)替代方法3:將license.txt內容作為string.xml的string,如:

<stringname="license_content">使用者協議

\n \n一、服務條款的確認和接納

\n…

</string>

需要注意的是:string裡需要加\n作為分行符號,原來txt裡的分行符號在取得string後無效。

不可取方法4:每次讀取4096位元組,以UTF8轉碼,最後連接字串。因為漢字可能被截斷,導致4096的倍數附近的中文可能出現亂碼。

private String readUserAgreementFromAsset(String assetName) {

         StringBuilder sb = newStringBuilder("");

         String content ="";

         try {

                   InputStream is= getAssets().open(assetName);

                   if (is != null){

                            DataInputStream dIs = new DataInputStream(is);

                            byte[] buffer = new byte[1024*4];

                            int length = 0;

                            while ((length = dIs.read(buffer)) >0) {

                                      content =EncodingUtils.getString(buffer, 0, length, "UTF-8");

                                     sb.append(content);

                            }

                    is.close();

                   }

         } catch (IOException e) {

                   e.printStackTrace();

         }

         return sb.toString();

}

 

二、Android中讀寫檔案

(1) 從resource中的raw檔案夾中擷取檔案並讀取資料(資源檔只能讀不能寫,\res\raw\test.txt)

String res = "";

try{

InputStream in = getResources().openRawResource(R.raw.test);

int length = in.available();

byte [] buffer = newbyte[length];

in.read(buffer);

res = EncodingUtils.getString(buffer,"UTF-8");//選擇合適的編碼,如果不調整會亂碼

in.close();

}catch(Exception e){

e.printStackTrace();

}

(2) 從asset中擷取檔案並讀取資料(資源檔只能讀不能寫,\assets\test.txt)

與raw檔案夾類似,只是:

InputStream is = getAssets().open(“test.txt”);

(3) 私人檔案夾下的檔案存取(/data/data/包名/files/test.txt)

使用openFileOutput寫檔案:

public void writeFileData(String fileName,String message){

        try{

             FileOutputStream fout =openFileOutput(fileName,MODE_PRIVATE);

        byte [] bytes =message.getBytes();

        fout.write(bytes);

        fout.close();

        }

    catch(Exception e){

        e.printStackTrace();

    }

}

使用openFileInput讀檔案:

public String readFileData(String fileName){

    String str = “”;

        try{

             FileInputStream fin =openFileInput(fileName);

        int length = in.available();

        byte [] bytes = newbyte[length];

        fin.read(bytes);

        str = EncodingUtils.getString(bytes,"UTF-8");

        fin.close();

        }

    catch(Exception e){

        e.printStackTrace();

}

return str;

}

(4) sdcard目錄下的檔案存取(/mnt/sdcard/)

使用FileOutputStream寫檔案:

public void writeFile2Sdcard(String fileName,String message){

    try{

             FileOutputStream fout = new FileOutputStream(fileName);

        byte [] bytes =message.getBytes();

        fout.write(bytes);

        fout.close();

        }

    catch(Exception e){

        e.printStackTrace();

    }

}

使用FileInputStream讀檔案:

public String readFileFromSdcard(String fileName){

    String res="";

    try{

        FileInputStream fin = newFileInputStream(fileName);

        int length =fin.available();

        byte [] buffer = newbyte[length];

        fin.read(buffer);

        res =EncodingUtils.getString(buffer, "UTF-8");

        fin.close();

    }

    catch(Exception e){

         e.printStackTrace();

    }

    return res;

}

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.