代碼如下:
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("文件寫入成功!");
}
}