2016年11月9日水曜日

Android 文件保存,文件读取

Android 文件保存,文件读取
使用内部存储
https://developer.android.com/guide/topics/data/data-storage.html#filesInternal

使用文件名称和操作模式调用 openFileOutput()。 这将返回一个 FileOutputStream。
使用 write() 写入到文件。
使用 close() 关闭流式传输。


public class MainActivity extends AppCompatActivity {

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

    protected void GetUser() {
        try {
            FileInputStream fis = new FileInputStream(new File(this.getFilesDir(), "user.csv"));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = fis.read(buff)) != -1) {
                baos.write(buff, 0, len);
            }
            System.out.println(baos.toString());
            JSONObject jde = new JSONObject(baos.toString());
            TextView tv1 = (TextView) findViewById(R.id.textView2);
            tv1.setText(jde.getString("userName"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void Userinfo() {
        JSONObject j = new JSONObject();
        JSONObject j2 = new JSONObject();
        try {
            j.put("userName", "sun");
            j.put("password", "12345");
            j2.put("phone1", "99999");
            j2.put("Phone2", "88808880");
            j.put("Phones", j2);
            File f = new File(this.getFilesDir(), "user.csv");
            FileOutputStream fos = new FileOutputStream(f);
            fos.write((j.toString()).getBytes());
            fos.close();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

0 件のコメント: