java读写删除文件及不同系统下的换行问题

读写文件有很多种方式,这里只记录一种

读文件 // 一次性读完

    public static String readFile() {
        String str = "";
        File file = new File("文件路径");
        try {
            FileInputStream in = new FileInputStream(file);
            int size = in.available();//文件长度
            byte[] buffer = new byte[size];
            in.read(buffer);
            in.close();
            str = new String(buffer, "utf-8");
            str = str.replaceAll("\r\n","\n");//某些换行问题解决,根据需求而定
        } catch (IOException e) {
            return null;
        }
        return str;
    }

写文件:

public static void outFile(String s) {
        File file = new File("生成的文件路径");
        try (FileOutputStream fop = new FileOutputStream(file)) {
            // 文件不存在,创建文件
            if (!file.exists()) {
                file.createNewFile();
            }
            // get the content in bytes
            byte[] contentInBytes = s.getBytes();
 
            fop.write(contentInBytes);
            fop.flush();
            fop.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

linux 和unix下换行符为:"\n"
windows下的换行符为:"\r\n"
如果需要把文件内容插入到数据库,可根据需求互换两种系统下的换行符。

删除文件代码如下:

   /**
     * 删除文件
     * 
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath)
    {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
            file.delete();
            flag = true;
        }
        return flag;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值