【问题标题】:How do I open an image in the default image viewer using Java on Windows?如何在 Windows 上使用 Java 在默认图像查看器中打开图像?
【发布时间】:2011-04-28 20:57:08
【问题描述】:

我有一个按钮来查看附加到日志条目的图像,当用户单击该按钮时,我希望它在 Windows 计算机上用户的默认图像查看器中打开图像?

我如何知道默认图像查看器中的哪个查看器?

现在我正在做这样的事情,但它不起作用:

String filename = "\""+(String)attachmentsComboBox.getSelectedItem()+"\"";
Runtime.getRuntime().exec("rundll32.exe C:\\WINDOWS\\System32\\shimgvw.dll,ImageView_Fullscreen "+filename);

不起作用是指它没有任何作用。我试图在命令行中运行该命令,但什么也没发生。没有错误,什么都没有。

【问题讨论】:

    标签: java windows image


    【解决方案1】:

    尝试使用 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.");
     }
    }
    

    这将启动与文件扩展名关联的默认照片查看器。

    更好的方法是使用 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.");
     }
    }
    

    Launch the application associated with a file extension

    【讨论】:

    • 第一个在 XP 上就像一个魅力,但还没有在 Vista 或 Win7 上检查过。我也可以试试第二个。为什么第二种方法会更好?
    • 因为它使用常规的 Java SE 类 (1.6),如果支持文件类型,它可以在其他平台上运行。
    【解决方案2】:

    您可以使用Desktop 类来满足您的需要,打开系统相关的应用程序。

    File file = new File( fileName );
    Desktop.getDesktop().open( file );
    

    【讨论】:

      【解决方案3】:

      另一个在 Windows XP/Vista/7 上运行良好的解决方案,可以打开任何类型的文件(url、doc、xml、图像等)

      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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-20
        • 1970-01-01
        • 1970-01-01
        • 2023-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多