Json讀寫當地文件完成代碼。本站提示廣大學習愛好者:(Json讀寫當地文件完成代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是Json讀寫當地文件完成代碼正文
import java.io.*;
/**
* Created by tang on 14-3-1.
*/
public class JsonUtils {
//從給定地位讀取Json文件
public static String readJson(String path){
//從給定地位獲得文件
File file = new File(path);
BufferedReader reader = null;
//前往值,應用StringBuffer
StringBuffer data = new StringBuffer();
//
try {
reader = new BufferedReader(new FileReader(file));
//每次讀取文件的緩存
String temp = null;
while((temp = reader.readLine()) != null){
data.append(temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//封閉文件流
if (reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data.toString();
}
//給定途徑與Json文件,存儲到硬盤
public static void writeJson(String path,Object json,String fileName){
BufferedWriter writer = null;
File file = new File(path + fileName + ".json");
//假如文件不存在,則新建一個
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//寫入
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(json.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(writer != null){
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// System.out.println("文件寫入勝利!");
}
}