当前位置: 首页 > 知识库问答 >
问题:

使用Java文件方法从temp创建new之前删除文件

丁振海
2023-03-14

我在下面的代码中尝试在temp目录中创建新文件,它是xml文件,并且工作正常。

现在,每次运行代码时,我都希望在创建新的xml文件之前从这个temp目录中删除以前的xml文件,因为xml文件很大,可能会占用我的临时空间。xml文件具有特定的命名约定life.*。xml。所以它应该删除所有的life.*。xml文件。

我不确定我们是否可以使用tempFile。deleteOnExit()在这里或如何使用它,因为我对java文件处理非常陌生,不知道在代码中做什么和在哪里做更改:

*/
@Slf4j
public class InputConsumer implements Runnable {

    public static final String XML_SUFFIX = ".xml";

    private void processlifeZipFile() {        //check the number of line in xml input zip file processed
        final AtomicBoolean isInsideLeiRecord = new AtomicBoolean();
        isInsideLeiRecord.set(false);
        final StringBuilder currentLeiRecordXml = new StringBuilder();
        try (FileSystem zipFs = FileSystems.newFileSystem(jobRunner.getInputZipPath(), null);   //check the zip file
             Stream<String> lines = Files.lines(xmlFileFromLeiZipFile(zipFs))) {  //streaming the lines inside xml file
            AtomicInteger processedLinesCounter = new AtomicInteger();
            AtomicInteger currentLineNumber = new AtomicInteger();
            lines
                    .sequential()
                    .forEach(handleLineAndIncrementLineNumber(isInsideLeiRecord, currentLeiRecordXml, processedLinesCounter, currentLineNumber))
            ;
            log.info("{} lines of XML file inside life input ZIP file {} processed.", processedLinesCounter.get(), jobRunner.getInputZipPath() //number of lines processed in xml file
            );
        } catch (IOException e) {
            throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
        }
    }
    private Path xmlFileFromLeiZipFile(FileSystem zipFs) {       //extracts the xml file from zip file
        log.info("Input file {} exists: {}", jobRunner.getInputZipPath(), Files.exists(jobRunner.getInputZipPath()));
        Path tmpXmlPath = createTmpXmlFile("life__" + System.currentTimeMillis());
        for (Path rootDir : zipFs.getRootDirectories()) {
            try (Stream<Path> files = treeAt(rootDir)) {
                log.info("Trying to extract life XML file from ZIP file into {}.", tmpXmlPath);
                final Path xmlFileInsideZip = files
                        .filter(isNotADir())
                        .filter(Files::isRegularFile)
                        .findFirst()
                        .orElseThrow(() -> new IllegalStateException("No file found in LEI ZIP file."));
                log.info("Path to life XML file inside ZIP file: {}.", xmlFileInsideZip);
                return copyReplacing(xmlFileInsideZip, tmpXmlPath);
            }
        }
        throw new IllegalStateException("No file found in LEI ZIP file " + jobRunner.getInputZipPath() + ".");
    }
    

    private static Path createTmpXmlFile(final String prefix) {
        try {
            log.info("Creating temporary file {}{}", prefix, XML_SUFFIX);
            return Files.createTempFile(prefix, XML_SUFFIX);
        } catch (IOException e) {
            throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
        }
    }
    
    @NotNull
    private static Path copyReplacing(Path from, Path to) {
        requireNonNull(from, "Trying to copy from a path, which is null to path " + to + ".");   //trying to copy file where no xml file exist in root directory
        requireNonNull(to, "Trying to copy from path " + from + " to a path, which is null.");
        try {
            return Files.copy(from, to, REPLACE_EXISTING);
        } catch (IOException e) {
            throw new IllegalStateException("Cannot copy from " + from + " to " + to + ". ", e);
        }
    }
}

共有1个答案

鲁霄
2023-03-14
Andrew, Please try the below code change done in method processlifeZipFile() and see if it works.

private void processlifeZipFile() {        //check the number of line in xml input zip file processed
        final AtomicBoolean isInsideLeiRecord = new AtomicBoolean();
        isInsideLeiRecord.set(false);
        final StringBuilder currentLeiRecordXml = new StringBuilder();
        Object jobRunner;
        try (FileSystem zipFs = FileSystems.newFileSystem(jobRunner.getInputZipPath(), null);   //check the zip file
                java.nio.file.Path tmpXMLFilePath = xmlFile`enter code here`FromLeiZipFile(zipFs); // Change
             Stream<String> lines = Files.lines(tmpXMLFilePath)) {  //streaming the lines inside xml file
            AtomicInteger processedLinesCounter = new AtomicInteger();
            AtomicInteger currentLineNumber = new AtomicInteger();
            lines
                    .sequential()
                    .forEach(handleLineAndIncrementLineNumber(isInsideLeiRecord, currentLeiRecordXml, processedLinesCounter, currentLineNumber))
            ;
            log.info("{} lines of XML file inside life input ZIP file {} processed.", processedLinesCounter.get(), jobRunner.getInputZipPath() //number of lines processed in xml file
            );
            Files.delete(tmpXMLFilePath); // change
        } catch (IOException e) {
            throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
        }
    }

编辑----

我创建了一个新方法来删除除新的temp xml文件以外的所有其他文件。

void deleteXMLFiles(Path xmlPath) {
        try {
            final List<Path> pathsToDelete = Files.list(xmlPath.getParent()).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
            for(Path path : pathsToDelete) {
                if (path.equals(xmlPath)) {
                    System.out.println("Skipping newly created XML file");
                    continue;
                }
                Files.delete(path);
                System.out.println("Deleting -> " + path.toString());
            }
        }catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }

将"Files.delete(tmpXMLFilePath);//Change"行替换为调用以tmpXMLFilePath为参数的新创建的方法。

deleteXMLFiles(tmpXMLFilePath);

有关更多详细信息,请参阅此答案:https://stackoverflow.com/a/47994874/13677537

编辑2----

修改了方法deleteXMLFiles(),以在删除之前检查文件名模式:

void deleteXMLFiles(Path xmlPath) {
        try {
            final List<Path> pathsToDelete = Files.list(xmlPath).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
            for (Path path : pathsToDelete) {
                String xmlFileName = path.toString();
                if (Pattern.matches(".*life__.*.xml", xmlFileName)) {
                    Files.delete(path);
                    System.out.println("Deleting -> " + xmlFileName);
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

修改了processlifeZipFile()方法调用以在创建新文件之前删除临时XML文件:

private void processlifeZipFile() {        //check the number of line in xml input zip file processed
        final AtomicBoolean isInsideLeiRecord = new AtomicBoolean();
        isInsideLeiRecord.set(false);
        final StringBuilder currentLeiRecordXml = new StringBuilder();
        
        // Delete the old temp XML Files before starting the processing
        deleteXMLFiles(Paths.get(System.getProperty("java.io.tmpdir")));
        
        try (FileSystem zipFs = FileSystems.newFileSystem(jobRunner.getInputZipPath(), null);   //check the zip file
             Stream<String> lines = Files.lines(xmlFileFromLeiZipFile(zipFs))) {  //streaming the lines inside xml file
            AtomicInteger processedLinesCounter = new AtomicInteger();
            AtomicInteger currentLineNumber = new AtomicInteger();
            lines
                    .sequential()
                    .forEach(handleLineAndIncrementLineNumber(isInsideLeiRecord, currentLeiRecordXml, processedLinesCounter, currentLineNumber))
            ;
            log.info("{} lines of XML file inside life input ZIP file {} processed.", processedLinesCounter.get(), jobRunner.getInputZipPath() //number of lines processed in xml file
            );
        } catch (IOException e) {
            throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
        }
    }
 类似资料:
  • 我正在C:drive文件夹中创建一个名为abc的dat文件,如下所示,现在我的文件每天都会生成,假设我的文件是今天生成的,然后tommrow也会像往常一样生成,但在生成tommrow时,我必须确保删除前一天的文件,因为该文件夹中的空间有限,每次需要执行此检查时,前一天的文件都会从该文件夹中删除,请建议如何实现这一点。。

  • 本文向大家介绍php文件夹的创建与删除方法,包括了php文件夹的创建与删除方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了php文件夹的创建与删除方法。分享给大家供大家参考。具体如下: 1、创建文件夹 2、创建文件夹,递归式创建 3、删除文件夹 希望本文所述对大家的php程序设计有所帮助。

  • 问题内容: 在Java中,我想删除包含文件和文件夹的文件夹中存在的所有内容。 此代码不起作用,执行此操作的最佳方法是什么? 问题答案: 如果您使用Apache Commons IO,那么它是单线的: 请参阅FileUtils.deleteDirectory() 番石榴曾经支持类似的功能: 几个版本之前已将其从Guava中删除。 虽然以上版本非常简单,但也很危险,因为它在不告诉您的情况下做出了许多假

  • 我正在使用gradle构建一个Spring Boot应用程序,我希望从war中删除文件,因为该文件将从外部加载(它运行在tomcat容器中,而不是嵌入式的)。 我查看了StackOverflow和Gradle文档,试图找出该做什么,但我不知道该绑定到哪个阶段,以及在创建war之前还是之后排除该文件。处理文件似乎也有多种方法。 我相信Maven使用作为等价物。

  • 我正在写一个涉及多个客户的应用程序。一个客户端使用FTP将文件上传到服务器,然后另一个客户端下载并删除该文件。我使用FTP服务器作为一种中间人来交换信息,因为我不希望用户必须向前移植。我已经知道如何上传文件,但我不知道如何删除文件。使用FTP删除文件的命令是: 我试过这么做,但没有成功。以下是我尝试过的代码: 我有一种感觉 我在这个网站上读到了关于类似问题的其他问题,所有的回答都告诉我使用图书馆。