写一个简单的工具类,只需要传入需要写入的对象和写入的地址即可
public class OperationFileUtil {
/**
* 写入本地文件
* @param object
* @param path
* @return
*/
static public Boolean writeFile(Object object , String path){
String s = JSON.toJSONString(object);
int i = judgeThePath(path);
File file = new File(path);
try (FileOutputStream fileOutputStream = new FileOutputStream(file)){
byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
fileOutputStream.write(bytes);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
/**
* 判断传入路径的文件夹和文件是否存在,不存在则创建
* @param path
* @return
*/
static int judgeThePath(String path){
File file = new File(path);
if (!file.exists() && !file.isDirectory()) {
log.info("文件夹不存在创建文件夹");
file.getParentFile().mkdirs();
}
if (!file.exists()){
log.info("文件不存在,创建文件");
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return 1;
}
}

本文介绍如何使用Java将对象转换并保存到本地文件。提供了一个实用工具类,该类接受对象和目标文件路径作为参数,实现对象的序列化。

4021

被折叠的 条评论
为什么被折叠?



