Java对文件操作包括CSV文件读写、文件压缩、文件下载

设计背景

支持测试一个Job。抓取一些数据。包括文件和数据库数据。

使用的Jar包

  • commons-csv
  • commons-io

使用Apache Commons CSV

共享资源CSV以逗号分隔值(CSV)格式的变体读取和写入文件。

最常见的 CSV 格式在 CSV 格式类中预定义

文档

用户指南中提供了该功能的概述。还提供各种项目报告

Javadoc API 文档可在线获取:

Apache Commons IO

Apache Commons IO是一个实用程序库,用于帮助开发IO功能。

主要包括六个领域:

  • io - 此包定义用于处理流、读取器、写入器和文件的实用程序类。
  • 比较器 - 此软件包为文件提供了各种比较器实现。
  • file - 此软件包在java.nio.file领域提供扩展。
  • filefilter - 此包定义一个接口 (IOFileFilter),它结合了 FileFilter 和 FilenameFilter。
  • function - 此包为 lambda 表达式和方法引用定义仅 IO 相关的功能接口。
  • input - 此包提供输入类的实现,例如 InputStream 和 Reader。
  • input.buffer - 此包提供缓冲输入类的实现,例如 CircularBufferInputStream 和 PeekableInputStream。
  • monitor - 此软件包提供用于监视文件系统事件(目录和文件创建、更新和删除事件)的组件。
  • output - 此包提供输出类的实现,如 OutputStream 和 Writer。
  • 序列化 - 此包提供了一个用于控制类的反序列化的框架。

释放

共享资源 IO 2.11.0 (需要 Java 8)

共享资源 IO 2.11.0 至少需要 Java 8 - 立即下载!

查看发行说明和 Javadoc API 文档

程序代码

        下载文件

@Test
public void readData() {
        try {
            // 定义CSV格式
            CSVFormat csvFormat = CSVFormat.Builder.create(CSVFormat.DEFAULT).setHeader().build();
            // 指定读取的文件
            FileReader reader1 = new FileReader("E:\\data\\coc_t_coc_voucher.csv");

            //以指定的CSV格式 解析文件并获取记录集
            List<CSVRecord> records1 = csvFormat.parse(reader1).getRecords();

            // 设置文件保存的父路径
            String fileParentPath1 = "E:\\file\\coc_t_coc_voucher";

            // 使用CompletableFuture 以异步方式提交任务[使用到了ForkJoinPool]
            CompletableFuture<Void> download1 = new CompletableFuture<>().runAsync(() -> {
                records1.parallelStream().forEach(cSVRecord -> {
                    // 从记录集的某一条记录中获取url
                    String fileUrl = cSVRecord.get("f_upload_url");
                    // 下载文件的逻辑
                    downloadFile(fileUrl, fileParentPath1);
                });
            });

            try {
                // 让 CompletableFuture 任务执行
                CompletableFuture.allOf(download1).get();

            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static void downloadFile(String fileUrl, String fileParentPath) {
        try {
            // 从url截取文件名字 xxx.word
            int start = fileUrl.lastIndexOf("/");
            String fileName = fileUrl.substring(start + 1);

            // 利用IOUtils 直接将url资源解析成字节
            byte[] bytes = IOUtils.toByteArray(new URL(URLFIX + fileUrl));

            File parent = new File(fileParentPath);
            File file = new File(parent, fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            // FileOutputStream指定了文件,并利用 IOUtils将字节写入流中
            IOUtils.write(bytes, fileOutputStream);
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

        压缩文件

    @Test
    public void zip() {
        try {
            // filePath1:要压缩的[目录] zipFile1:指定生产的文件
            File filePath1 = new File("E:\\file\\coc_t_coc_voucher");
            File zipFile1 = new File("E:\\file\\coc_t_coc_voucher.zip");

            // 创建Zip文件专门的输出流
            ZipOutputStream zipOutputStream1 = new ZipOutputStream(new FileOutputStream(zipFile1));
            // 获取文件夹下的文件和目录.以流的方式依次处理
            Arrays.stream(filePath1.listFiles()).forEach(file -> {
                // 具体的压缩细节
                zip(zipOutputStream1, file);
            });
            System.out.println("完成zipFile1");
            // 及时关闭输出流
            zipOutputStream1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 具体的压缩细节
    private void zip(ZipOutputStream zipOutputStream, File file) {
        try {
            new CompletableFuture<>().runAsync(() -> {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                try {
                    // 压缩文件-关键代码:
                    //  1.要写入ZIP文件条目 2.写入
                    zipOutputStream.putNextEntry(zipEntry);
                    IOUtils.copy(new FileInputStream(file), zipOutputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

        上传至FastDFS(具体细节不太一样)

    @Test
    public void upload() {
        try {
            HfsClient client = new HfsClient(15000, 30000, "utf-8", new String[]{"fastdfs:22122"}, 8080, false);

            String url1 = client.upload("coc_t_coc_voucher.zip", "E:\\file\\coc_t_coc_voucher.zip", "987");
            System.out.println(url1);
//            group1/M00/00/00/CioAnWK0H8eAaqDZLmkc5Ruisik322.zip
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        更新CSV文件

    // group1/M00/12/CD/Cp8L4GA2FZCAZG9GAAAYADbqU1o777.xls ->
    // group1/M00/00/00/Cp8L4GA2FZCAZG9GAAAYADbqU1o777.xls
    @Test
    public void writeCSV() {
        // 统一的URL前缀
        String urlPrefix = "group1/M00/00/00/";
        // 指定CSV格式-设置表头
        CSVFormat cSVFormat1 = CSVFormat.Builder.create(CSVFormat.DEFAULT).setHeader().build();
        try {
            // 读取源文件
            FileReader reader1 = new FileReader("E:\\data\\coc_t_coc_voucher.csv");

            List<CSVRecord> records1 = cSVFormat1.parse(reader1).getRecords();

            // csv要写的文件(新文件 db_gmcf_crf_t_crf_offline_source_file.csv , 以EXCEL格式写)
            CSVPrinter printer2 = new CSVPrinter(
                    new FileWriter("E:\\toDataBase\\crf_t_crf_offline_source_file.csv"),
                    CSVFormat.EXCEL);

            for (int i = 0; i < records2.size(); i++) {
                // 具体对每一条数据处理的逻辑
                // 源文件coc_t_coc_voucher.csv 共有10列。 都写进去,第8列是url。 是拼接阶段字符串
                String column7 = records2.get(i).get(7);
                printer2.printRecord(
                        records2.get(i).get(0),
                        records2.get(i).get(1),
                        records2.get(i).get(2),
                        records2.get(i).get(3),
                        records2.get(i).get(4),
                        records2.get(i).get(5),
                        records2.get(i).get(6),
                        i == 0 ? column7 : urlPrefix.concat(column7.substring(column7.lastIndexOf("/")+1)),
                        records2.get(i).get(8),
                        records2.get(i).get(9));
            }

            // 切记 刷新流+关闭流 不然数据不全内存泄露
            csvPrinter3.close(true);

        } catch (Exception e) {
            e.getMessage();
        }
    }

案例数据

f_id,f_voucher_no,f_settle_no,f_upload_name,f_upload_url,f_created_time,f_modified_time
7,ykhk20181220001,COC18122020000000024,jian,group7/M00/00/00/Cp8L4FwjXbSAShviAAK4euxR8tQ103.png,2018-12-26 18:53:44,2018-12-26 18:53:44
14,yicaxichai20181228,COC18122804000000003,liul,group7/M00/00/00/Cp8L4VwnGlmAd26oAAA0E9AmqE8756.jpg,2018-12-29 14:56:10,2018-12-29 14:56:10

发文助手会检测您的文章标题、错别字、内容质量,助您提升文章质量。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值