Android儲存讀取txt檔案

綠色落日發表於2017-11-23

做個記錄

在Android中,raw資料夾跟assets資料夾都是隻能讀取不能寫入的,

儲存檔案內容

 

public void save(List<String> datas){
        if (datas != null) {
            try {
                FileWriter fw = new FileWriter("/data/data/com.joni.test/recently.txt");
                //寫入資料並換行
                for (int i = 0; i < datas.size(); i++) {
                    fw.write(datas.get(i)+"\r\n");
                }
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "****Save Error****");
            }
        }
}


讀取檔案內容

 

 

public List<String> loadFile(String fileName){
        List<String> lists = new ArrayList<>();
        try {
            File file = new File("/data/data/com.joni.test/"+fileName);
            InputStream instream = new FileInputStream(file);
            if (instream != null) {
                InputStreamReader inputreader
                        = new InputStreamReader(instream, "GBK");
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line = "";
                while ((line = buffreader.readLine()) != null) {
                    lists.add(line);
                }
                instream.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "****Load " + fileName + " Error****");
        }
        return lists;
}

 

 

 

相關文章