2014-09-04 23 views
2

我想打開一個圖像文件,打包在一個.jar文件中,使用我運行程序的計算機的默認圖像查看器。從java輸入流打開圖像文件

我發現了很多關於如何訪問使用InputStream打包在一個jar中的文件的答案,但是如何使用該InputStream打開這些文件?

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

我可以將此轉換爲ImageImageIconBufferedImage但如何我進一步打開默認的圖像瀏覽器的形象呢?

我的類名是「測試」,我試圖訪問的圖像是C:\Users\Pranav\Documents\NetBeansProjects\Test\src\test\DSC_6283.jpg

任何幫助,將不勝感激。

回答

5

純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()); 
} 

編輯:

 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

更合適!:)完美的作品!你能解釋一下這些線是如何工作的嗎? 'while((len = imageStream.read(buffer))!= -1)'byte [] buffer = new byte [1024];' 'int len;' ' {' 'out.write(buffer,0,len);' '}' – Pranav 2014-09-06 02:17:11

+0

@Pranav添加評論 – Andreas 2014-09-08 16:02:57

+0

非常感謝! :D @Andreas – Pranav 2014-09-08 16:26:07