Java 读写文件工具类

今天简单写了一下读写文件用的工具类,方便后面开发或者测试时直接使用。

import lombok.Cleanup;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {

    //逐行读取文件内容返回内容列表
    public static List<String> readLine(String path){
        List<String> list = new ArrayList<>();
        try {
            //@Cleanup lombok用法 自动关闭IO
            @Cleanup BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
            String line = "";
            while ((line = reader.readLine()) != null){
                if (line.trim().length()>0){
                    list.add(line);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }


    //读取文件内容并返回
    public static String readToString(String fileName){
        String encoding = "UTF-8";
        //new File对象
        File file = new File(fileName);
        //获取文件长度
        Long filelength = file.length();
        //获取同长度的字节数组
        byte[] filecontent = new byte[filelength.intValue()];
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            in.read(filecontent);
            return new String(filecontent,encoding);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            try {
                in.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }

    //向文件里写入内容
    public static void saveAsFileWriter(String path, String content){
        File file = new File(path);
        //如果目录不存在 创建目录
        try {
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        FileWriter fileWriter = null;
        try {
            // true表示不覆盖原来的内容,而是加到文件的后面。若要覆盖原来的内容,直接省略这个参数就好
            fileWriter = new FileWriter(path, false);
            fileWriter.write(content);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                fileWriter.flush();
                fileWriter.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值