首先先来写一个类来做测试
public class student{
private String name;
private String age;
private String sex;
get...... set......
}
这里就可以输出JSON文件了
import com.alibaba.fastjson.JSONObject;
import entity.student;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public void write(HttpSession session){//不需要HttpSession的话可以直接写绝对路径即可
student stu=new student();
stu.setAge("12");
stu.setName("测试");
stu.setSex("男");
String jsonString = JSONObject.toJSONString(stu,true);
String pathFile=session.getServletContext().getRealPath("/test/"); //注意 这个文件夹要是没有的话是会报错的
File file=new File(pathFile);
if (!file.exists()) { //所以在这里必须提前创建好文件夹
file.mkdirs();
}
Path ConfPath = Paths.get(pathFile, "test.json");
try {
if (!Files.exists(ConfPath)){
Files.createFile(ConfPath);
}
} catch (Exception e) {
System.out.println("创建配置文件失败");
}
try {
Files.write(ConfPath, Json.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
} catch (Exception ex) {
System.out.println("写入配置文件失败");
}
}
以上有几个需要注意的点:
-
首先JSON所在的文件夹一定要存在,不然会报错。
-
还有就是可以去看一下这个内容的特性StandardOpenOption.CREATE 再次生成JSON文件内容的话是覆盖生成的,而不是重新生成文件,假如说你之前生成的内容比较长,之后的比较短的话,就会出现覆盖掉一半的情况,下次读取的话肯定是读取不进来的。需要注意一下这个点。
下面是这些枚举的详解
public enum StandardOpenOption implements OpenOption {
/**
* 以读的方式连接文件。
*/
READ,
/**
* 以写的方式连接文件。
*/
WRITE,
/**
* 以追加的方式连接文件,不会覆盖文件原本内容,在后面追加。 */
APPEND,
/**
* 如果文件存在并且以WRITE的方式连接时就会把文件内容清空,文件设置为0字节大小。
* 如果文件只以READ连接 时,该选项会被忽略。
*/
TRUNCATE_EXISTING,
/**
* 创建一个文件,如果文件已存在,就打开文件连接。与CREATE_NEW同时存在时该选项会被忽略。
*/
CREATE,
/**
* 创建一个文件,如果文件已存在,如果已经存在会抛异常。
*/
CREATE_NEW,
/**
* 通道关闭时删除文件
*/
DELETE_ON_CLOSE,
/**
* 创建稀疏文件,与CREATE_NEW选项配合使用。
*/
SPARSE,
/**
* 要求每次写入要把内容和元数据刷到存储设备上。
*/
SYNC,
/**
* 要求每次写入那内容刷到存储设备上
*/
DSYNC;
}
读取JSON文件
private String read(HttpSession session) {
String pathFile=session.getServletContext().getRealPath("/test/");
Path ConfPath =Paths.get(pathFile, "test.json");
byte[] bytes = new byte[]{};
try {
bytes = Files.readAllBytes(ConfPath);
} catch (Exception e) {
System.out.println("读取文件失败");
}
String jsonString = new String(bytes);
return jsonString;
}
同样不需要HttpSession 的话可以直接写绝对路径