考点:
- 内部存储
- 缓冲区的内容写入文件
- 文件的内容写入缓冲区
- JSON解析
- 通过安卓内置的org.json包解析(该包提供了JSONObject和JSONArray两个类)
- 通过Google开源的Gson库解析 *必考
- SharedPreferences解析
- 用SharedPreferences存数据
- 用SharedPreferences读数据
一、内部存储
FileOutputStream fos = openFileOutput(String name, int mode);FileInputStream fis = openFileInput(String name);
mode的值:
MODE_PRIVATE
MODE_WORLD_READABLE
MODE_WORLD_WRITABLE
MODE_APPEND
1.缓冲区的内容写入文件
FileOutputStream fos;String fileName = "hh.txt";String content = "Hello,World!";try {fos = openFileOutput(fileName, MODE_PRIVATE);//创建文件输出流fos.write(content.getBytes());//以字节格式将content内容写入文件fos.close();//关闭文件}catch(Exception e){e.printStackTrace();}
2.文件的内容写入缓冲区
FileInputStream fis;String content = "";String fileName = "hh.txt";try{fis = openFileInput(fileName);//创建输入流byte[] buffer = new byte[fis.available()];//创建字节数组作为缓冲区&获得文件长度fis.read(buffer);//文件内容读入数组中content = new String(buffer);//数组中内容转换为字符串读入content中fis.close()//关闭文件}catch(Exception e){e.printStackTrace();}
二、JSON解析
//要解析的JSON数据{ "name" : "zhangsan", "age" : 27, "married" : true }//json1[ 16,2,26 ] //json2
//1.通过安卓内置的org.json包解析, 该包提供了JSONObject和JSONArray两个类
//对象JSONObject jsonObj = new JSONObject(json1);String name = jsonObj.optString("name");int age = jsonObj.optInt("age");boolean married = jsonObj.optBoolean("married");//数组int [] arr = new int[];JSONArray jsonArr = new (json2);for(int i=0; i<jsonArr.length(); i++){arr[i] = jsonArr.optInt(i);}
2.通过Google开源的Gson库解析 *必考
//Gson gson = new Gson();// = gson.fromJson(json文件名, 类名);//对象Gson gson = new Gson();Person person = gson.fromJson(json1, person.class);//数组Gson gson = new Gson();Type listType = new TypeToken< List<Integer> >(){}.getType();List<Integer> ages = gson.fromJson(json2, listType);
三、SharedPreferences解析
用SharedPreferences存数据
SharedPreferences sp = new SharedPreferences("name", MODE_PRIVATE);//创建SharedPreferences,输入参数(文件名,读写模式)SharedPreferences.Editor editor = sp.edit();//创建编辑器editor.putString("name","zhangsan");//用putXX(key,value)写入编辑器editor.putInt("age",27);editor.remove("key");//删除键对应的值editor.clear();//清空所有键值editor.commit();//必须提交才能保存编辑的数据
用SharedPreferences读数据
SharedPreferences sp = new SharedPreferences("name", MODE_PRIVATE);String data = sp.getString("name",null);
