在我的端点中,我接收Base64格式的字符串形式的文件内容. 解压在Seven Zip库上运行得很好,没有问题. 但在执行完这行代码后

archive = SevenZip.openInArchive(null, new RandomAccessFileInStream(
                        new RandomAccessFile(file, "r")));

Java无法删除文件,原因如下:

java.nio.file.FileSystemException: myFile.RAR: The process cannot access the file because it is being used by another process

我曾try 使用Junrar库,但Seven Zip运行得更好(支持RAR5,并将较少损坏的文件识别为Junrar).

-pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>demo</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding</artifactId>
            <version>16.02-2.01</version>
        </dependency>
        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding-all-platforms</artifactId>
            <version>16.02-2.01</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

以下是dto:

public record UploadDto(
        @NotNull
        String name,
        @NotNull
        String data) {
}

以下是带有逻辑的控制器:

import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

@RestController
public class TestController {
    private final Logger log = LoggerFactory.getLogger(TestController.class);

    @PostMapping("/upload")
    public void extractRar(@RequestBody UploadDto dto){
        byte[] decodedBytes = Base64.getDecoder().decode(dto.data());
        try {
            String filePath = dto.name();
            Files.write(Paths.get(filePath), decodedBytes);
            log.info("File saved successfully to: " + filePath);
            File file = new File(filePath);
            IInArchive archive;
            try {
                archive = SevenZip.openInArchive(null, new RandomAccessFileInStream(
                        new RandomAccessFile(file, "r")));
                log.info(String.valueOf(archive.getNumberOfItems()));
            } catch (SevenZipException | FileNotFoundException e) {
                throw new RuntimeException(e);
            }
            archive.close();

            // 1 method
            Files.delete(Path.of(filePath));

            // 2 method
            if (file.delete()) {
                log.info("file deleted successfully");
            } else {
                log.error("failed to delete the temporary file used for unzipping");
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

请求正文示例:

{
  "name": "myFile.RAR",
  "data": "UmFyIRoHAM+QcwAADQAAAAAAAABTL3QgkC8AFAAAABQAAAACTeXQiWmKL1cdMAoAIAAAAG15RmlsZS50eHQAsAA/PXJhciBkYXRhIG1vY2sgaGVyZQ0KxD17AEAHAA=="
}

我try 了两种删除文件的方法,但似乎都不起作用. 此外,我也没有找到任何使用字节数组或InputStream打开存档的方法. 如果我可以在提取内容后删除文件,或者在不将文件保存在本地的情况下提取内容,问题就会得到解决. 如有任何帮助或 idea ,我们将不胜感激! 操作系统Windows 10

推荐答案

在线找到的示例,请在关闭存档后关闭文件.

如下所示(根据您的需要,您可能希望分别try 捕获Close()调用):

@PostMapping("/upload")
public void extractRar(@RequestBody UploadDto dto){
    byte[] decodedBytes = Base64.getDecoder().decode(dto.data());
    try {
        String filePath = dto.name();
        Files.write(Paths.get(filePath), decodedBytes);
        log.info("File saved successfully to: " + filePath);
        File file = new File(filePath);
        IInArchive archive;
        RandomAccessFile randomAccessFile;
        try {
            
            randomAccessFile = new RandomAccessFile(file, "r");
            archive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
            log.info(String.valueOf(archive.getNumberOfItems()));
        } catch (SevenZipException | FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        archive.close();
        randomAccessFile.close();

        // 1 method
        Files.delete(Path.of(filePath));

        // 2 method
        if (file.delete()) {
            log.info("file deleted successfully");
        } else {
            log.error("failed to delete the temporary file used for unzipping");
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Java相关问答推荐

计算战舰沉船/船只的问题(Java)

收听RDX中用户数据的变化

gitlab ci不会运行我的脚本,因为它需要数据库连接'

JPackaged应用程序启动MSI调试,然后启动System. exit()

如何在Android上获取来电信息

如果一个子类没有构造函数,超类也没有构造函数,那么为什么我可以构造子类的实例呢?

需要一个找不到的jakarta.sistence.EntityManager类型的Bean

如何确定springboot在将json字段转换为Dto时如何处理它?

基于调车场算法的科学计算器

如何正确创建序列图?

如何在ApachePOI中将图像添加到工作表的页眉?

如何从Keyloak映射Hibernate实体中的用户

使用PDFBox从PDF中删除图像

如何在JavaFX循环中完美地制作一个AudioClip/MediaPlayer?

X=x*0.90;产生有损转换误差.X*=0.90;不是.为什么?

如何获得凌空cookies ,并设置它在下一个请求- android

寻找Thread.sky()方法的清晰度

接受类及其接口的Java类型(矛盾)

在Java中使用StorageReference将数据从Firebase存储添加到数组列表

为什么child-pom会创建一个新版本