目录
- 1 问题
- 2 实现
1 问题
Java 实现解压 TR_2023063012.tar.gz 这种格式的压缩包
递归文件夹,找到tar.gz 格式的压缩包,并且进行解压,解压到这个压缩包所在的文件夹下
2 实现
public static void main(String[] args) {String depth = "D:\\data";ArrayList<String> strings = new ArrayList<>();List<String> gz = FileUtils.listFile(strings, new File(depth), true, "gz");for (String item:gz){File file = new File(item);File parentFile = file.getParentFile();String absolutePath = parentFile.getAbsolutePath();try {uncompressTarGz(item, absolutePath);System.out.println("File uncompressed successfully.");} catch (IOException e) {e.printStackTrace();}System.out.println(item);}// String inputFilePath = "D:\\059\\data\\RAIN_GRIB\\2023060200\\TR_2023060200.tar.gz"; // 压缩包文件路径
// String outputFolderPath = "D:\\059\\data\\RAIN_GRIB\\2023060200\\"; // 解压输出文件夹路径
//
// try {
// uncompressTarGz(inputFilePath, outputFolderPath);
// System.out.println("File uncompressed successfully.");
// } catch (IOException e) {
// e.printStackTrace();
// }}private static void uncompressTarGz(String inputFilePath, String outputFolderPath) throws IOException {try (FileInputStream fileInputStream = new FileInputStream(inputFilePath);BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);GzipCompressorInputStream gzipInputStream = new GzipCompressorInputStream(bufferedInputStream);TarArchiveInputStream tarInputStream = new TarArchiveInputStream(gzipInputStream)) {TarArchiveEntry entry;while ((entry = (TarArchiveEntry) tarInputStream.getNextEntry()) != null) {if (!entry.isDirectory()) {File outputFile = new File(outputFolderPath, entry.getName());createParentDirectory(outputFile);try (OutputStream outputStream = new FileOutputStream(outputFile)) {byte[] buffer = new byte[1024];int length;while ((length = tarInputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, length);}}}}}}private static void createParentDirectory(File file) {File parent = file.getParentFile();if (parent != null && !parent.exists()) {parent.mkdirs();}}