如何在Windows上使用Java在默认图像查看器中打开图像?
我有一个按钮可以查看附加到日志条目的图像,当用户单击该按钮时,我希望它在Windows计算机上的用户默认图像查看器中打开图像 如何知道默认图像查看器中的哪个查看器 现在我正在做这样的事情,但不起作用:如何在Windows上使用Java在默认图像查看器中打开图像?,java,windows,image,Java,Windows,Image,我有一个按钮可以查看附加到日志条目的图像,当用户单击该按钮时,我希望它在Windows计算机上的用户默认图像查看器中打开图像 如何知道默认图像查看器中的哪个查看器 现在我正在做这样的事情,但不起作用: String filename = "\""+(String)attachmentsComboBox.getSelectedItem()+"\""; Runtime.getRuntime().exec("rundll32.exe C:\\WINDOWS\\System32\\shimgvw.dll
String filename = "\""+(String)attachmentsComboBox.getSelectedItem()+"\"";
Runtime.getRuntime().exec("rundll32.exe C:\\WINDOWS\\System32\\shimgvw.dll,ImageView_Fullscreen "+filename);
我所说的“不起作用”是指它没有任何作用。我试图在命令行中运行命令,但什么也没发生。没有错误,什么都没有。尝试使用CMD/C启动
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.");
}
}
请参见您可以使用该类来打开与系统关联的应用程序,该类可以完全满足您的需要
File file = new File( fileName );
Desktop.getDesktop().open( file );
另一个在Windows XP/Vista/7上运行良好的解决方案,可以打开任何类型的文件(url、文档、xml、图像等)
第一个在XP上很有魅力,但还没有在Vista或Win7上验证过。我也可以试试第二个。为什么第二种方法会更好呢?因为它使用的是一个普通的JavaSE类(1.6),如果支持文件类型,它可以在其他平台上工作。
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
}