How to open image in default image viewer using Java on Windows?

Do I have a button for viewing an image attached to a journal entry, and when the user clicks this button, I want it to open the image in the default image viewer on a Windows computer?

How do I know which viewer is in the default image viewer?

Right now I am doing something like this, but this does not work:

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

And it doesn’t work, I mean that it does nothing. I tried to run the command only on the command line, and nothing happened. No mistake, nothing.

+6
source share
3 answers

Try using 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 launch the default photo viewer associated with the file extension.

It is best 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 file extension related application .

+11
source

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

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

Another solution that works well in 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 } 
+1
source

Source: https://habr.com/ru/post/886919/


All Articles