How do I open an image in the default image viewer using Java on Windows?

后端 未结 3 1233
鱼传尺愫
鱼传尺愫 2021-01-12 06:03

I have a button to view an image attached to a log entry and when the user clicks that button I want it to open the image in the user\'s default image viewer on a Windows ma

相关标签:
3条回答
  • 2021-01-12 06:40

    Another solution that works well on Windows XP/Vista/7 and can open any type of file (url, doc, xml, image, etc.)

    Process p;
    try {
        String command = "rundll32 url.dll,FileProtocolHandler \""+ new File(filename).getAbsolutePath() +"\"";
    
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
    
    } catch (IOException e) {
        // TODO Auto-generated catch block
    
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
    }
    
    0 讨论(0)
  • 2021-01-12 06:47

    Try with the CMD /C START

    public class Test2 {
      public static void main(String[] args) throws Exception {
        String fileName = "c:\\temp\\test.bmp";
        String [] commands = {
            "cmd.exe" , "/c", "start" , "\"DummyTitle\"", "\"" + fileName + "\""
        };
        Process p = Runtime.getRuntime().exec(commands);
        p.waitFor();
        System.out.println("Done.");
     }
    }
    

    This will start the default photo viewer associated with the file extension.

    A better way is to use java.awt.Desktop.

    import java.awt.Desktop;
    import java.io.File;
    
    public class Test2 {
      public static void main(String[] args) throws Exception {
        File f = new File("c:\\temp\\test.bmp");
        Desktop dt = Desktop.getDesktop();
        dt.open(f);
        System.out.println("Done.");
     }
    }
    

    See Launch the application associated with a file extension

    0 讨论(0)
  • 2021-01-12 06:57

    You can use the Desktop class which does exactly what you need, to open system associated application.

    File file = new File( fileName );
    Desktop.getDesktop().open( file );
    
    0 讨论(0)
提交回复
热议问题