当前位置:   article > 正文

Java RAR解析

Java RAR解析

maven依赖:
<!-- https://mvnrepository.com/artifact/com.github.junrar/junrar -->
<dependency>
    <groupId>com.github.junrar</groupId>
    <artifactId>junrar</artifactId>
    <version>2.0.0</version>
</dependency>

在使用该jar包进行解析时候引发的内存爆满机器卡死,如图:

看源码发现每一次解压都new了一个线程,但是却没有对线程进行管理,改造如下:

代码示例:

  1. private void extractRarFile(InputStream inputStream) {
  2. UnRarUtils archive = null;
  3. InputStream is = null;
  4. try {
  5. // 解析文件
  6. archive = new UnRarUtils(inputStream);
  7. if (archive == null) {
  8. throw new FileNotFoundException(" not found!");
  9. }
  10. if (archive.isEncrypted()) {
  11. throw new Exception(" is encrypted!");
  12. }
  13. List<FileHeader> files = archive.getFileHeaders();
  14. if (files.size() == 0) {
  15. return ;
  16. }
  17. for (FileHeader fh : files) {
  18. try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:\\子文件")))){
  19. // 判断子文件是否加密
  20. if (fh.isEncrypted()) {
  21. continue;
  22. }
  23. // 获取文件名
  24. String fileName;
  25. if (StringUtils.isNotBlank(fh.getFileNameW())) {
  26. fileName = fh.getFileNameW();
  27. } else if (StringUtils.isNotBlank(fh.getFileNameString())) {
  28. fileName = fh.getFileNameString();
  29. } else {
  30. continue;
  31. }
  32. // 获取子文件字节流
  33. is = archive.getInputStream(fh);
  34. byte[] bytes = IOUtils.toByteArray(is);
  35. if (bytes.length <= 0) {
  36. continue;
  37. }
  38. is.close();
  39. // 输出子文件
  40. writer.write(new String(bytes));
  41. return;
  42. } catch (Exception e) {
  43. throw new RuntimeException("exception");
  44. } finally {
  45. try {
  46. if (is != null) {
  47. is.close();
  48. }
  49. } catch (Exception e) {
  50. }
  51. }
  52. }
  53. archive.close();
  54. inputStream.close();
  55. } catch (Exception e) {
  56. } finally {
  57. try {
  58. if (archive != null) {
  59. archive.close();
  60. }
  61. if (inputStream != null) {
  62. inputStream.close();
  63. }
  64. } catch (IOException e) {
  65. }
  66. }
  67. return;
  68. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/388106
推荐阅读
相关标签
  

闽ICP备14008679号