Java 创建文件&写数据到文件

今天有一个任务就是接收数据,然后将数据写到文件,在网上查看了很多,也尝试也很多,都不太对,总是报找不到文件,弄了一晚上,写了一个比较严谨的代码,然后就没有出过错了,就想起了大学学的程序的健壮性,严谨== 正确

private static void createFile(byte[] data) {
    BufferedOutputStream bos = null;

    File file = null;
    try {
        // start -------------------创建文件的严谨
        File dir = new File(FILE_PATH);
        if (dir.exists() || dir.mkdirs()) { // 严谨 == 正确
            System.out.println(dir.getPath());
        }

        file = new File(FILE_PATH, "data_" + count + ".txt");

        if (file.exists() || file.createNewFile()) {// 严谨 == 正确
            System.out.println(file.getName());
        }
        // end --------------------

        bos = new BufferedOutputStream(new FileOutputStream(file));
        bos.write(data);

        bos.flush();

        System.out.println("success " + count);
        count++;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值