安卓開發數據持久化技術——內部文件存儲

爲了提高開發水平,準備把郭神第二行代碼的demo都碼一遍並記錄下來。此篇文章是:安卓開發數據持久化技術——內部文件存儲。
廢話不多說,直接上代碼。

/**
 * ****************************數據持久化技術一********************************
 * 內部文件存儲讀寫,適用於存儲一些簡單的文本內容
 * 路徑:/data/data/<packagename>/files/目錄下*需要root權限才能查看到
 * ****************************數據持久化技術一********************************
 */
public class FileActivity extends AppCompatActivity {

    private EditText etFile1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);
        etFile1 = ((EditText) findViewById(R.id.etFile1));
        String inputText = load();
        if (inputText!=null && inputText!=""){
            etFile1.setText(inputText);
            etFile1.setSelection(inputText.length());
            Toast.makeText(this, "讀取內部文件成功", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String inputText = etFile1.getText().toString();
        saveFile(inputText);
    }

    /**
     * 存儲內容到內部存儲
     * @param inputText
     */
    private void saveFile(String inputText){
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try {
            fos = openFileOutput("data", Context.MODE_PRIVATE);
            bw = new BufferedWriter(new OutputStreamWriter(fos));
            bw.write(inputText);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (bw!=null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 讀取內部文件內容
     * @return
     */
    private String load(){
        FileInputStream fis = null;
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            fis = openFileInput("data");
            br = new BufferedReader(new InputStreamReader(fis));
            String line = "";
            while ((line = br.readLine())!=null){
                sb.append(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (br!=null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章