本文主要是介绍java实现rar格式转换为zip,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
maven 依赖
<dependency><groupId>com.github.junrar</groupId><artifactId>junrar</artifactId><version>7.5.4</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version></dependency>
- hutool-all 不是必须的,如果不想引入,下面代码中的对应位置自行修改即可。
实现代码
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.github.junrar.Archive;
import com.github.junrar.exception.RarException;
import com.github.junrar.rarfile.FileHeader;import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;public class RarToZip {public static void main(String[] args) {String rootDir = "F:\\tmp\\1\\RarToZip\\";String destRootDir = "F:\\tmp\\1\\RarToZip\\";FileUtil.walkFiles(new File(rootDir),file -> {if (file.getName().endsWith(".rar")) {try {unrar(file.getPath(), destRootDir);} catch (RarException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}}});File file1 = new File(destRootDir);File[] files = new File(destRootDir).listFiles(File::isDirectory);if (files == null){System.out.println("no file");return;}for (File file : files) {if (file.isDirectory()){System.out.println("zip:"+file.getPath());ZipUtil.zip(file);}}}public static void unrar(String rarFilePath, String outputDir) throws RarException, IOException {System.out.println("unrar " + rarFilePath + " to " + outputDir);File outputFolder = new File(outputDir);if (!outputFolder.exists()) {outputFolder.mkdirs();}try (Archive archive = new Archive(new FileInputStream(rarFilePath))) {FileHeader fileHeader;while ((fileHeader = archive.nextFileHeader()) != null) {String fileName = outputDir + File.separator + new String(fileHeader.getFileName().getBytes(), StandardCharsets.UTF_8);if (fileHeader.isDirectory()) {new File(fileName).mkdirs();} else {new File(fileName).getParentFile().mkdirs();try (InputStream fileInputStream = archive.getInputStream(fileHeader);FileOutputStream fileOutputStream = new FileOutputStream(fileName)) {byte[] buffer = new byte[1024];int read;while ((read = fileInputStream.read(buffer)) != -1) {fileOutputStream.write(buffer, 0, read);}}}}}}
}
总结
有需要的同学,自取。如有问题可以在评论区联系我。如果你觉得这篇文章对你有帮助请点赞收藏关注。
这篇关于java实现rar格式转换为zip的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!