天天看點

Android存儲資料到檔案

MainActivity.java:

package com.miao.filestrore;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void stroe(View view) {
        try {
            OutputStream os = openFileOutput("datafile.data",MODE_APPEND);
            os.write("Hello World ...你是我的小蘋果。\n".getBytes("utf-8"));
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void read(View view) {
        try {
//            1.通過緩沖數組來讀取和存儲
//            InputStream is = openFileInput("datafile.data");
//            ByteArrayOutputStream content = new ByteArrayOutputStream();
//            byte[] buf = new byte[1024];
//            int length = 0;
//            while((length=is.read(buf))!=-1){
//                content.write(buf,0,length);
//            }
//            byte[] info = content.toByteArray();
//            String result = new String(info,"utf-8");
//            Log.i("miao",result);
//            is.close();

//            2.先用available()方法擷取檔案大小,定義指定大小的緩沖數組,一次性完成。

              InputStream is = openFileInput("datafile.data");
              byte[] buf = new byte[is.available()];
              is.read(buf);
              String content = new String(buf,"utf-8");
              Log.i("miao",content);
              is.close();

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