2013/01/21

Android Internal storage

寫入前是沒有任何檔案的


寫入後可以很清楚看到有一個新資料夾『files』,將檔案test1.txt寫入進去




在透過讀取的方式將檔案讀取出來並寫show出內容





package com.cyfang.internal;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    private Button btn_Save = null;
    private Button btn_Load = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_Save = (Button) findViewById(R.id.button_save);
        btn_Load = (Button) findViewById(R.id.button_load);
        btn_Save.setOnClickListener(clickListener);
        btn_Load.setOnClickListener(clickListener);
    }

    private Button.OnClickListener clickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.button_save:
                saveFile();
                break;
            case R.id.button_load:
                readFile();
                break;
            }
        }
    };

    private void saveFile() {
        try {
            FileOutputStream fileOutputStream = openFileOutput("test1.txt",
                    Context.MODE_PRIVATE);
            fileOutputStream.write("0123456789".getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Toast.makeText(MainActivity.this, "儲存成功", Toast.LENGTH_LONG).show();
    }

    private void readFile() {
        String temp = null;
        try {
            FileInputStream fileInputStream = openFileInput("test1.txt");
            int length = fileInputStream.available();
            byte[] buffer = new byte[length];
            fileInputStream.read(buffer);
            fileInputStream.close();
            temp = new String(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Toast.makeText(MainActivity.this, "儲存內容為:" + temp, Toast.LENGTH_LONG)
                .show();
    }
}