android 讀取txt檔案內容

來源:互聯網
上載者:User

標籤:

Android的res檔案夾是用來儲存資源的,可以在res檔案夾下建立一個raw檔案夾,放置在raw檔案夾下的內容會被原樣打包,而不會被編譯成二進位檔案,並且可以通過R檔案進行很方便地訪問。比如我們可以將更新資訊、著作權資訊等放到txt檔案中,然後放到raw檔案中,然後很方便地進行訪問。

 

在raw中放入一個a.txt檔案,然後就可以在Activity中使用getResources().openRawResource(R.raw.a);方法擷取一個此檔案的InputStream類,而後就可以很方便地進行讀寫a.txt了。
1     InputStream inputStream = getResources().openRawResource(R.raw.a);
View Code

 

一個擷取InputStream中字串內容的方法:傳入一個InputStream,返回其中的常值內容。

 1     public static String getString(InputStream inputStream) { 2         InputStreamReader inputStreamReader = null; 3         try { 4             inputStreamReader = new InputStreamReader(inputStream, "gbk"); 5         } catch (UnsupportedEncodingException e1) { 6             e1.printStackTrace(); 7         } 8         BufferedReader reader = new BufferedReader(inputStreamReader); 9         StringBuffer sb = new StringBuffer("");10         String line;11         try {12             while ((line = reader.readLine()) != null) {13                 sb.append(line);14                 sb.append("\n");15             }16         } catch (IOException e) {17             e.printStackTrace();18         }19         return sb.toString();20     }
View Code

 

以gbk編碼讀取內容,不同的文字檔可能編碼不同,如果出現亂碼,可能需要調整編碼。

1 inputStreamReader = new InputStreamReader(inputStream, "gbk");
View Code

 

android 讀取txt檔案內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.