如何在 Windows 上使用 Java 在默认图像查看器中打开图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5824916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I open an image in the default image viewer using Java on Windows?
提问by Brian T Hannan
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 machine?
我有一个按钮可以查看附加到日志条目的图像,当用户单击该按钮时,我希望它在 Windows 计算机上的用户默认图像查看器中打开图像?
How do I know which viewer in the default image viewer?
我如何知道默认图像查看器中的哪个查看器?
Right now I'm doing something like this but it doesn't work:
现在我正在做这样的事情,但它不起作用:
String filename = "\""+(String)attachmentsComboBox.getSelectedItem()+"\"";
Runtime.getRuntime().exec("rundll32.exe C:\WINDOWS\System32\shimgvw.dll,ImageView_Fullscreen "+filename);
And by doesn't work I mean it doesn't do anything. I tried to run the command just in the command line and nothing happened. No error, nothing.
和不起作用我的意思是它没有做任何事情。我试图在命令行中运行该命令,但什么也没发生。没有错误,什么都没有。
回答by RealHowTo
Try with the CMD /C START
尝试使用 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.
更好的方法是使用 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.");
}
}
回答by OscarRyz
回答by eee
Another solution that works well on Windows XP/Vista/7 and can open any type of file (url, doc, xml, image, etc.)
另一个在 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
}