java 自定义工具类 对File进行操作

package com.xtql.safe.utils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileUtil {

    // 创建文件目录
    public static void newFilePath(String filePath) throws IOException {
        File file = new File(filePath);

        if (!file.exists()) {
            // 如果路径不存在,则创建路径
            file.mkdirs(); // 创建多层目录
        }

    }

    //根据文件目录删除文件
    public static void delectFile(String filePath) throws IOException {
        File chunkFile = new File(filePath);
        if (chunkFile.exists()) {
            if (!chunkFile.delete()) {
                throw new RuntimeException("无法删除文件: " + filePath);
            }
        }
    }

    //获取文件目录下所有文件数量
    public static int getTotalChunks(String filePath) {
        File directory = new File(filePath).getParentFile();
        File[] files = directory.listFiles();

        if (files != null) {
            return files.length;
        } else {
            return 0;
        }
    }


    //获取文件拓展名称
    public static String extractFileExtension(String filePath) {
        String fileName = new File(filePath).getName();
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex != -1) {
            return fileName.substring(dotIndex + 1);
        }
        return "";
    }


    //提取文件目录
    public static String extractDirectory(String filePath) {
        Path path = Paths.get(filePath);
        Path parentPath = path.getParent();

        if (parentPath != null) {
            return parentPath.toString();
        } else {
            return "";
        }
    }

    //去除文件拓展名
    public static String removeExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex != -1) {
            return fileName.substring(0, lastDotIndex);
        }
        return fileName;
    }

    //修改文件后缀名
    public static String replaceFileExtension(String filename, String newExtension) {
        // 获取文件名的最后一个点的位置
        int dotIndex = filename.lastIndexOf(".");

        // 如果文件名中没有点,则返回原始文件名
        if (dotIndex == -1) {
            return filename;
        }

        // 获取原始文件名(不包括后缀名)
        String basename = filename.substring(0, dotIndex);

        // 拼接新的文件名
        String newFilename = basename + "." + newExtension;

        return newFilename;
    }

    // 判断文件是否需要解压
    public static boolean isZipFile(File file) {
        String fileName = file.getName();
        return fileName.endsWith(".zip") || fileName.endsWith(".ZIP");
    }

    public static void extractFile(ZipInputStream zipInputStream, String entryPath) throws IOException {
        File outputFile = new File(entryPath);
        try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = zipInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }

    //文件解压方法 第一个参数 需要解压文件的路径  第二个参数 文件解压之后的路径  (压缩的方式有很多种不是所有都能解压)
    public static void unzipFile(String zipFilePath, String destDirPath) throws IOException {
        try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                String entryName = entry.getName();
                String entryPath = destDirPath + File.separator + entryName;
                if (entry.isDirectory()) {
                    createDirectory(entryPath);
                } else {
                    extractFile(zipInputStream, entryPath);
                }
                zipInputStream.closeEntry();
            }
        }
    }

    public static void createDirectory(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    //将源文件复制到目标文件
    public static void copyFile(String sourceFilePath, String destinationFilePath) throws IOException {
        File sourceFile = new File(sourceFilePath);
        File destinationFile = new File(destinationFilePath);

        if (!sourceFile.exists()) {
            throw new FileNotFoundException("Source file not found: " + sourceFilePath);
        }

        try (InputStream inputStream = new FileInputStream(sourceFile);
             OutputStream outputStream = new FileOutputStream(destinationFile)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }

    // 验证文件md5值
    private String calculateMD5(String filePath, MessageDigest md5Digest) throws IOException {
        InputStream inputStream = null;

        try {
            inputStream = Files.newInputStream(Paths.get(filePath));
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                md5Digest.update(buffer, 0, bytesRead);
            }

            byte[] digest = md5Digest.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值