java把对象写入本地文件

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

写一个简单的工具类,只需要传入需要写入的对象和写入的地址即可

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值