public void readAndWrite() throws IOException {
//文件路径
String path="D:\\contents.js";
//读取文件流
InputStream in=new FileInputStream(path);
//读取到的内容
String str=stream2String(in);
//此处是针对特定项目处理文件内容
JSONArray item = JSONArray.parseArray(str);
JSONObject item2 = (JSONObject) item.get(0);
item.add(JSONObject.parseObject(item2.toJSONString()));
//写入文件
FileOutputStream on =new FileOutputStream(path);
//写入文件
outStream(on,item);
}
private String stream2String(InputStream in) throws IOException {
//进行编码转换
BufferedReader bfReader = new BufferedReader(new InputStreamReader(in, "GB2312"));
按行读取数据
String line = bfReader.readLine();
//关闭文件流
bfReader.close();
return line;
}
private void outStream(FileOutputStream on, JSONArray item) throws IOException {
BufferedOutputStream bos=new BufferedOutputStream(on);
//按相应编码写入文件
bos.write(item.toString().getBytes("GB2312"));
//关闭文件流
bos.close();
}
文件读取及写入
于 2023-08-28 09:48:29 首次发布