Json reads and writes the local file implementation code
- 2020-04-01 03:01:52
- OfStack
import java.io.*;
public class JsonUtils {
//Read the Json file from the given location
public static String readJson(String path){
//Gets the file from the given location
File file = new File(path);
BufferedReader reader = null;
//Returns the value, using StringBuffer
StringBuffer data = new StringBuffer();
//
try {
reader = new BufferedReader(new FileReader(file));
//Cache for each file read
String temp = null;
while((temp = reader.readLine()) != null){
data.append(temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//Close file stream
if (reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data.toString();
}
//Given path with Json file, store to hard disk
public static void writeJson(String path,Object json,String fileName){
BufferedWriter writer = null;
File file = new File(path + fileName + ".json");
//If the file does not exist, create a new one
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//write
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(" file write Success! ");
}
}