2014-09-04 2 views
2

Я пытаюсь открыть файл изображения, который упакован в .jar-файл, используя средство просмотра изображений по умолчанию на компьютере, на котором я запускаю свою программу.Открытие файла изображения из java InputStream

Я нашел множество ответов о том, как обращаться к файлам, которые упакованы в банку с помощью InputStream, но как я могу открыть эти файлы с помощью этого InputStream?

InputStream imageStream = Test.class.getClass().getResourceAsStream("/test/DSC_6283.jpg"); 

я могу преобразовать это в Image, ImageIcon или BufferedImage, но, как я дальше открыть изображение в средстве просмотра изображения по умолчанию?

имя Мой класс «Test» и образ я пытаюсь получить доступ в C:\Users\Pranav\Documents\NetBeansProjects\Test\src\test\DSC_6283.jpg

Любая помощь будет оценена.

ответ

5

Pure Java:

public static void main(String... args) throws IOException { 
    InputStream imageStream = Test.class.getClass().getResourceAsStream("/test/DSC_6283.jpg"); 
    Path path = Files.createTempFile("DSC_6283", ".jpg"); 
    try (FileOutputStream out = new FileOutputStream(path.toFile())) { 
     byte[] buffer = new byte[1024]; 
     int len; 
     while ((len = imageStream.read(buffer)) != -1) { 
      out.write(buffer, 0, len); 
     } 
    } catch (Exception e) { 
     // TODO: handle exception 
    } 
    Desktop.getDesktop().open(path.toFile()); 
} 

Edit:

 byte[] buffer = new byte[1024]; //allocate an array of bytes to use as a buffer. 1024 bytes in this case 
     int len; //a variable to record the number of bytes actually read from the stream each loop 
     while ((len = imageStream.read(buffer)) != -1) { //InputStream.read(byte[]) reads bytes from the stream and places them into the buffer. It returns the number of bytes placed into the buffer, or -1 if there is nothing more to read. We store that result in len, and evaluate if we should stop looping (ie if the return is -1) 
      out.write(buffer, 0, len); //write to the output file, from the buffer, starting at position 0, through the number of bytes read 

Обратите внимание, что это плитка. Я украл эту версию от Easy way to write contents of a Java InputStream to an OutputStream

+0

Спасибо большое! :) Работает отлично! Не могли бы вы объяснить, как работают эти строки: 'byte [] buffer = new byte [1024];' 'int len;' 'while ((len = imageStream.read (buffer))! = -1) {' ' out.write (buffer, 0, len); ' '} ' – Pranav

+0

@Pranav добавил комментарии – Andreas

+0

Спасибо большое! : D @Andreas – Pranav

0
  1. Сохранить изображение локально (ех с:. \ My_image.jpg), который не находится в .jar файле
  2. Использование Runtime.getRuntime().exec("cmd your_command_here_to_open_image"); здесь ссылка для CMD команды на окнах: http://www.sevenforums.com/software/180378-where-windows-photo-viewer-default-location.html
+2

возможно, временная папка была бы более подходящей, чем C: \ – jtahlborn

Смежные вопросы