您的位置:首页 > 移动开发 > Android开发

Android编程权威指南-第十七章挑战练习

2015-08-05 14:47 381 查看
CriminalIntentJSONSerializer.java文件

package com.onevol.app;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import android.content.Context;
import android.os.Environment;

public class CriminalIntentJSONSerializer {

private Context mContext;
private String mFilename;

public CriminalIntentJSONSerializer(Context c, String f){
mContext = c;
mFilename = f;
}

public void saveCrimes(ArrayList<Crime> crimes) throws JSONException, IOException{
JSONArray array = new JSONArray();
for(Crime c : crimes)
array.put(c.toJSON());

Writer writer = null;
try{
OutputStream out = null;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//检测是否有sd卡
File sdCard = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), mFilename);//获取sd卡的绝对路径,就是全部的路径。
out = new FileOutputStream(sdCard);
}else{
out = mContext.openFileOutput(mFilename, Context.MODE_PRIVATE);
}
writer = new OutputStreamWriter(out);
writer.write(array.toString());
} finally {
if(writer != null)
writer.close();
}
}

public ArrayList<Crime> loadCrimes() throws IOException, JSONException{
ArrayList<Crime> crimes = new ArrayList<Crime>();
BufferedReader reader = null;
try{
InputStream in = null;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCard = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), mFilename);
in = new FileInputStream(sdCard);
}else{
in = mContext.openFileInput(mFilename);
}
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
jsonString.append(line);
}
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue();
for(int i = 0; i < array.length(); i++){
crimes.add(new Crime(array.getJSONObject(i)));
}
}catch(FileNotFoundException e){

}finally{
if(reader != null)
reader.close();
}
return crimes;
}
}


并在AndroidManifest.xml文件中声明权限

<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: