Deleting file if it crashes my app (2)
ok so i've nearly got this. But it seems there is some logic error that i can't get around. Note that i cannot use try/catch. No need to ask why
EDIT
for(String File : List){
        final String FilePath = getPath() + "/" + File;
        Render renderer = renderFile(FilePath);
        Runtime.getRuntime().addShutdownHook(new Thread(){
             public void run() {
                    deleteFile(FilePath);
                }
            });
        deleteFile(FilePath);
        updateReport(stuff);
        writeReportToFile(Report.toString(开发者_StackOverflow中文版));
I want it to delete the file that's causing my crash .. if the app crashes but it doesn't seem to be working. Am i calling it wrongly or what? confused
FINAL EDIT
OK after much toying around i finally got it to work!! Thanks everyone
From your last question I see, that you
- process images,
- one or more images will crash the JVM,
- we can't catch that exception/error and
- we want to delete the corrupt image on the next run
An easy solution goes like that:
- Each time, before you read bytes from an image file, persist the name of that image to a file (like: processingImage.txt)
- Each time, an image has been processed succesfully, delete processingImage.txt
- If the application crashes, then processingImage.txtcontains the name of the offending image
- If you start the application, check if processingImage.txtexists, read the name of the image, delete the image and deleteprocessingImage.txt.
I have a bad feeling about this, but you could add a shutdown hook on your application. (Be warned, while the shutdown hooks are processed, the only way to kill your application is via task manager - so be sure that your shutdown hook really works/does not take forever/does not cause deadlocks)
The following main
public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
                System.out.println("I'm called on shutown.");
            }
        });
    throw new RuntimeException("Uncaught Exception");
}
prints this:
Exception in thread "main" java.lang.RuntimeException: Uncaught Exception
    at stackoverflowtests.ShutdownHookTester.main(ShutdownHookTester.java:11)
I'm called on shutown.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论