json库的下载地址:https://mvnrepository.com/artifact/org.json/json/20180813
user.json放在项目的config资源文件夹下
public class JTest {
@Test
public void jsonTest() {
// String content = readJsonFile("config/user.json");
//
// JSONObject json = new JSONObject(content); //将json字符串转化成json对象
//
String jsonStr = "{'user':{'xrc':'123', 'lw':'123', 'zx':'123'}}";
writeJSON("config/user.json", jsonStr);
}
/***
* 给定一个文件路径,返回json的字符串形式
* @param fileName
* @return
*/
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 将json字符串写到文件名当中
* @param fileName
* @param jsonStr
*/
public static void writeJSON(String fileName, String jsonStr) {
try {
File jsonFile = new File(fileName);
FileWriter fileWriter = new FileWriter(jsonFile);
fileWriter.write(jsonStr);
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("没有写成功");
}
}
}