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

Android通过Json实现导入导出

2015-04-13 14:53 190 查看
// 导出文件
private void Export() {
filePath = null;

// 判断sd卡是否存在
boolean hasSDCard = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
if (hasSDCard) {

filePath = Environment.getExternalStorageDirectory().toString()
+ File.separator + "hello.txt";

try {
file = new File(Environment.getExternalStorageDirectory(),
"hello.txt");
if (file.exists()) {
file.delete();
}
FileOutputStream outStream = new FileOutputStream(file);
listNote = CreateData.getListData();
JSONArray jsonArray = new JSONArray();
try {
for (int i = 0; i < listNote.size(); i++) {
json = new JSONObject();
Bug.Print("" + listNote.size());
System.out.println("---->" + listNote.size());
json.put("Id", listNote.get(i).getId());
json.put("Colorid", listNote.get(i).getColorid());
json.put("Context", listNote.get(i).getContext());
json.put("Time", listNote.get(i).getTime());
Bug.Print(json.getString("Colorid"));
jsonArray.put(json);
}
String s = jsonArray.toString();
System.out.println(s);
outStream.write(s.getBytes());
} catch (JSONException e) {
e.printStackTrace();

}
Toast.makeText(this.owner, "", Toast.LENGTH_LONG).show();
outStream.close();
file.createNewFile();

} catch (Exception e) {
e.printStackTrace();
Bug.Print(e.getMessage());
}
// 提示框
AlertDialog.Builder builder = new Builder(this.owner);
builder.setMessage("导出成功");

builder.setTitle("已将文本文件(hello.txt)输出至SD卡" + file + "目录下");

builder.setPositiveButton("确认", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
}

// 导入文件
private void Introduction() {
/*

*/
try {

File urlFile = new File(Environment.getExternalStorageDirectory()
+ "/hello.txt");
InputStreamReader isr = new InputStreamReader(new FileInputStream(
urlFile), "UTF-8");
BufferedReader br = new BufferedReader(isr);
str = "";
String mimeTypeLine = null;

while ((mimeTypeLine = br.readLine()) != null) {
str = str + mimeTypeLine;

}
System.out.println(str);
JSONObject obj = null;
JSONArray jsonArray = null;

jsonArray = new JSONArray(str);
for (int i = 0; i < jsonArray.length(); i++) {
obj = jsonArray.getJSONObject(i);

strID = obj.getString("Context");
time = obj.getString("Time");
colorid = obj.getString("Colorid");

System.out.println(strID);
CreateData.InsetData(new Entity(strID, time, colorid));
}

Log.d("TAG", str);
} catch (Exception e) {

Toast.makeText(this.owner, "导入失败", Toast.LENGTH_LONG).show();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: