Java-自定义文件工具类

package com.wx;

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

/**
 * FileName: FileUtil
 * Author: mohe
 * Date: 2021/11/5 16:29
 * Description:
 */
public class FileUtil {
    private final File file;
    //要写入的String文本
    private String a;
    //文件路径
    private final String path;

    public FileUtil(String path, String a) throws IOException {
        file = new File(path);
        this.a = a;
        this.path = path;
    }
    public FileUtil(String path) throws IOException {
        file = new File(path);
        this.path = path;
    }

    public void createFile() throws IOException {
        file.delete();
        file.createNewFile();
    }

    public void writeFile(String a) throws IOException {
        FileWriter f = new FileWriter(file, true);
        f.write(a);
        f.close();
    }

    //读取文件写入list
    public List<String> readFile() throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        List<String> list = new ArrayList<>();
        String readStr;
        while ((readStr = reader.readLine()) != null) {
            list.add(readStr);
        }
        reader.close();
        if (reader == null) {
            reader.close();
        }
        return list;
    }

    public Integer lineNumber() throws IOException {

        LineNumberReader lnr = new LineNumberReader(new FileReader(new File(path)));
        lnr.skip(Long.MAX_VALUE);
        Integer ite = lnr.getLineNumber();
        return ite;
    }

    //执行创建、写入方法,覆盖原文件中文本
    public void updateFile() throws IOException {
        createFile();
        writeFile(a);
    }

    //test main
    public static void main(String[] args) {
        String filepath = "test.csv";
        String filepath1 = "test.txt";
        String a = "111\n" +
                "222\n" +
                "333";
        String ss=null;
        //测试获取文件行数并输出
        try {
            FileUtil file = new FileUtil(filepath);
            FileUtil file1 = new FileUtil(filepath1);
            file.createFile();
            int number = file1.lineNumber();
            List<String> list = file1.readFile();
            for (int i = 0; i <= number; i++) {
                System.out.println(list.get(i));
                ss=list.get(i);
                file.writeFile(ss+"\n");
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值