直接贴代码了,这个是用google提供的json库 gson 2.5 下载地址download
private void loadData(){
File fileDir = getFilesDir();
String fileDirString = fileDir.getPath();
String jsonFilePath = fileDirString + File.separator + FILE_NAME_JSON;
File jsonFile = new File(jsonFilePath);
if (jsonFile.exists() == false) {
try {
boolean bret = jsonFile.createNewFile();
if (false == bret) {
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
writeData(jsonFilePath);
readData(jsonFilePath);
}
private void writeData(final String jsonFilePath){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("id", "1222");
jsonObject.put("name", "Mrs Joden.");
jsonObject.put("phone", "224-33223624");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(jsonFilePath);
fileWriter.write(jsonObject.toString());
fileWriter.flush();
} catch (Exception e) {
// TODO: handle exception
}
finally{
if (null != fileWriter) {
try {
fileWriter.close();
fileWriter = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void readData(final String jsonFilePath){
InputStream inputStream = null;
String jsonString;
try {
inputStream = new FileInputStream(jsonFilePath);
int size = inputStream.available();
byte buffer[] = new byte[size];
inputStream.read(buffer);
jsonString = new String(buffer,"UTF-8");
} catch (Exception e) {
// TODO: handle exception
return;
}
finally{
if (null != inputStream) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
String s = jsonString;
}