Txt 和 Csv 文件读写操作

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.15.0</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.10.0</version>
</dependency>
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件工具类
 */
public class FileUtil {

    /**
     * txt 文件读取
     */
    public static List<String> txtReader(String filePath, int size) throws Exception {
        InputStream stream = FileUtils.openInputStream(new File(filePath));
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));

        List<String> datas = new ArrayList<>();
        if (size > 0) {
            // 获取第一行的数据当做字段
            System.out.println("header: " + reader.readLine());
            // 获取前 size 行数据
            for (int i = 1; i <= size; i++) {
                System.out.println("content: " + reader.readLine());
                datas.add(reader.readLine());
            }
        } else {
            // 获取全量数据
            String line;
            while ((line = reader.readLine()) != null) {
                datas.add(line);
            }
        }
        reader.close();
        return datas;
    }


    /**
     * csv 文件读取
     */
    public static List<String> csvReader(String filePath, int size) throws Exception {
        InputStream stream = FileUtils.openInputStream(new File(filePath));
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
        CSVParser parse = CSVFormat.EXCEL.parse(reader);

        List<String> datas = new ArrayList<>();
        int num = 0;
        for (CSVRecord record : parse.getRecords()) {
            StringBuilder resBuffer = new StringBuilder();
            for (int i = 0; i < record.size(); i++) {
                resBuffer.append(record.get(i)).append(",");
            }
            // 去掉末尾的逗号
            resBuffer.setLength(resBuffer.length() - 1);
            datas.add(resBuffer.toString());

            // 最多读取 size 条
            if (size > 0 && num == size) {
                break;
            }
            num++;
        }
        reader.close();
        return datas;
    }


    /**
     * txt 文件写入
     */
    public static void txtWriter(String filePath) throws Exception {
        String txtFile = filePath + ".txt";
        // true -> 追加 ; false -> 覆盖
        FileWriter writer = new FileWriter(txtFile, true);
        String data = "张三,25,男";
        writer.append(data);
        writer.append("\n");
        writer.close();
    }


    /**
     * csv 文件写入
     */
    public static void csvWriter(String filePath) throws Exception {
        String csvFile = filePath + ".csv";
        // true -> 追加 ; false -> 覆盖
        FileWriter writer = new FileWriter(csvFile, true);
        List<String> strList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            String data = "张三" + i + ",25,男";
            strList.add(data);
        }

        for (String str : strList) {
            writer.append(str);
            writer.append("\n");
        }
        writer.close();
    }


    /**
     * 加锁写入文件,追加写入
     */
    public static void lockWrite(String filePath, String data) {
        try (RandomAccessFile file = new RandomAccessFile(filePath, "rw");
             FileOutputStream outputStream = new FileOutputStream(file.getFD());
             OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
            FileChannel channel = file.getChannel();
            try (FileLock ignored = channel.lock()) {
                file.seek(file.length());
                writer.write(data);
                writer.write(System.lineSeparator());
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 加锁读取文件
     */
    public static List<String> lockRead(String filePath) {
        List<String> datas = new ArrayList<>();
        try {
            RandomAccessFile file = new RandomAccessFile(filePath, "rw");
            FileChannel channel = file.getChannel();
            try (FileLock ignored = channel.lock(0, Long.MAX_VALUE, true)) {
                String line;
                while ((line = file.readLine()) != null) {
                    datas.add(line);
                }
            }
            file.setLength(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return datas;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值