2015年9月18日 星期五

Android-讀寫文字檔案( Read / Write String in the file )

將文字資料寫入手機的方法

1 . 將字串寫入對應的檔案
/** 將資料寫入記憶卡內 */
public void writeInfo(String fileName, String strWrite)
{
    try {

        String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        String savePath = fullPath + File.separator + "/"+fileName+".txt";

        File file = new File(savePath);

        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(strWrite);
        bw.write(aa);

        bw.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

2 . 讀取檔案內的字串
/** 讀取記憶卡資料 */
public String readInfo(String fileName){

    BufferedReader br = null;
    String response = null;

    try {
        StringBuffer output = new StringBuffer();
        String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        String savePath = fullPath + File.separator + "/"+fileName+".txt";

        br = new BufferedReader(new FileReader(savePath));
        String line = "";
        while ((line = br.readLine()) != null) {
            output.append(line +"\n");
        }
        response = output.toString();
        br.close();

    } catch(FileNotFoundException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
    return response;
}

3 . 權限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


歡迎轉載,請註明出處。

沒有留言:

張貼留言