1. 程式人生 > >Android開發 讀取assets目錄下的txt檔案

Android開發 讀取assets目錄下的txt檔案

/**
     * 讀取assets下的txt檔案,返回utf-8 String
     * @param context
     * @param fileName 不包括字尾
     * @return
     */
    public static String readAssetsTxt(Context context,String fileName){
        try {
            //Return an AssetManager instance for your application's package
            InputStream is = context.getAssets().open(fileName+".txt"
); int size = is.available(); // Read the entire asset into a local byte buffer. byte[] buffer = new byte[size]; is.read(buffer); is.close(); // Convert the buffer into a string. String text = new String(buffer, "utf-8"); // Finally stick the string into the text view.
return text; } catch (IOException e) { // Should never happen! // throw new RuntimeException(e); e.printStackTrace(); } return "讀取錯誤,請檢查檔名"; }

直接上程式碼簡單粗暴