BIO合并某个目录下的所有文件

统计服务器日志,没有服务器权限,所以只能把日志文件下载到本地,进行合并后统计,下面为用nio合并某个目录下的所有文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.Optional;

public class Main {

    public static void main(String[] args) {
    // write your code here
//      String currentPath = Main.class.getResource("/").getPath();
//      System.out.println(currentPath);
//
        String currentPath = "C:\\Users\\wkgui\\Desktop\\服务器巡检\\jilin-4-24";
        File currentDirectory = new File(currentPath);
        if (!currentDirectory.isDirectory()){
            System.err.println("当前路径不合法");
            return;
        }


        File mergeFile = createMergeFile(currentPath);
        if (mergeFile == null){
            System.out.println("合并文件创建失败");
            return;
        }

        try(FileChannel mergeFileChannel = new FileOutputStream(mergeFile).getChannel()) {
            mergeFile(mergeFileChannel, new File(currentPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建合并的目标文件
     * @param path 文件平级路径
     * @return file
     */
    private static File createMergeFile(String path){
        String[] dirs = path.split("\\\\");
        int lastDirLen = dirs[dirs.length-1].length();
        File mergeFile = new File(path.substring(0, path.length()-lastDirLen) + "/merge-file-" + System.currentTimeMillis() + ".txt");
        if (mergeFile.exists()){
            mergeFile.delete();
        }
        try {
            mergeFile.createNewFile();
        } catch (IOException e) {
            System.err.println("文件创建失败");
            return null;
        }
        return mergeFile;
    }

    /**
     * 递归合并文件夹下的所有文件
     * @param mergeFileChannel 输出文件channel
     * @param file file
     */
    private static void mergeFile(FileChannel mergeFileChannel, File file){
        //是文件直接添加到file
        if (file.isFile()){
            try(FileChannel fileChannelOut = new FileInputStream(file).getChannel()) {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                while (fileChannelOut.read(buffer) != -1){
                    buffer.flip();
                    mergeFileChannel.write(buffer);
                    buffer.clear();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (file.isDirectory()){
            Arrays.stream(Optional.ofNullable(file.listFiles()).orElse(new File[0]))
                    .forEach(obj -> mergeFile(mergeFileChannel, obj));
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值