简体   繁体   English

简单 java 打开文件的过程莫名其妙结束

[英]Simple java Process for opening files ends inexplicably

Part of my program needs to open files and documents, wait until user manually closes them and then deletes them.我的部分程序需要打开文件和文档,等到用户手动关闭它们然后删除它们。 So I have a separate thread that just opens the file with Process class and waits for the Process to end, than it deletes the file.所以我有一个单独的线程,它只使用 Process class 打开文件并等待 Process 结束,然后删除文件。 Here is the code:这是代码:

@Override
    public void run() {
        try {
            ProcessBuilder ps=new ProcessBuilder("cmd.exe","/C",path);
            Process p=ps.start();
            p.waitFor();
            ps=new ProcessBuilder("cmd.exe","/C","del",path);
            p=ps.start();
            p.waitFor();
        }catch(IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

This works with pdf, txt or docx documents, but it doesn't work with images, the png or jpg files.这适用于 pdf、txt 或 docx 文档,但不适用于图像、png 或 jpg 文件。 In case of an image, thread opens the image with Windows Photos program but doesn't wait for process to end, instead it acts like the process is already dead and proceedes to delete it right after opening it, so instead of an image I see this:在图像的情况下,线程使用 Windows 照片程序打开图像,但不等待进程结束,而是表现得好像进程已经死了,并在打开它后立即删除它,所以我看到的不是图像这: 在此处输入图像描述

My question is why does it act like the Process is immediately dead when I open PNG or JPG files, but it works normally when I open PDF, TXT, DOCX files?我的问题是为什么当我打开 PNG 或 JPG 文件时它表现得像进程立即死亡,但当我打开 PDF、TXT、DOCX 文件时它却正常工作? Is the problem in Windows Photos viewer maybe?可能是 Windows 照片查看器中的问题?

I managed to open image files adding我设法打开图像文件添加

Thread.sleep(5000);

right after opening an image, but it still deletes the image after 5 seconds, it just somehow still stays open in Windows Photos viewer even if it has been deleted.打开图像后立即,但它仍会在 5 秒后删除图像,即使它已被删除,它仍然以某种方式在 Windows 照片查看器中保持打开状态。 Clearly this is not the solution, I want to properly solve this situation.显然这不是解决方案,我想妥善解决这种情况。

You can delete the file when your program exits.您可以在程序退出时删除该文件。 Why do you want that the File is delete right after the file is closed?为什么要在文件关闭后立即删除文件?

File file = new File("path");
file.deleteOnExit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM