java中退出for循环时删除文件

发布于 2025-01-20 10:28:33 字数 788 浏览 3 评论 0原文

我创建了一种从Web下载文件的方法,然后使用for Loop我获取该下载文件的绝对路径并将其加载到PDFBox中以执行进一步的操作。但是,我希望在执行操作时自动删除该文件。但是我编写的代码不允许我这样做。但是,如果我使用for循环删除PDF,则可以使用。有解决方案吗?

 for (File pdfs : Objects.requireNonNull(folder.listFiles())) {
                String desiredPdf = pdfs.getAbsolutePath();
                System.out.println(desiredPdf);
                pdfs.deleteOnExit();
    
                File baseFile = new File(desiredPdf);
                PDDocument document = PDDocument.load(baseFile);
                document.setAllSecurityToBeRemoved(true);
    
                String pdfContent = new PDFTextStripper().getText(document);
                System.out.println(pdfContent);
    
                Assert.assertTrue(pdfContent.contains("Imperfection"));
    
    
            }

I created a method that downloads a file from the web, then using a for loop I get the absolute path of that downloaded file and load it into pdfbox to perform further actions. However, I want the file to be automatically deleted when the action is performed. But the code I wrote doesn't allow me to do so. However, if I use the for loop to delete the pdf it works. Any solution?

 for (File pdfs : Objects.requireNonNull(folder.listFiles())) {
                String desiredPdf = pdfs.getAbsolutePath();
                System.out.println(desiredPdf);
                pdfs.deleteOnExit();
    
                File baseFile = new File(desiredPdf);
                PDDocument document = PDDocument.load(baseFile);
                document.setAllSecurityToBeRemoved(true);
    
                String pdfContent = new PDFTextStripper().getText(document);
                System.out.println(pdfContent);
    
                Assert.assertTrue(pdfContent.contains("Imperfection"));
    
    
            }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文