2017-02-17 44 views
0

我想通過下面的代碼將圖像(從網址)保存到我的磁盤。 我希望代碼將此圖像保存在java代碼的位置。例如,如果源java代碼位於D:\ example \ saveimage.java中,則該圖像將保存在D:\ example \ image.jpg中。此位置可能會在安裝過程中更改。 我該怎麼做?它的Java代碼是什麼? 謝謝保存圖像(從一個網址)到java代碼位置

public static void main(String[] args) throws Exception { 
    String imageUrl ="http://imgs.yooz.ir/yooz/walls/yooz-950625.jpg"; 

    String destinationFile = "E:\\Picture\\Wallpaper.jpg"; 
    //destinationFile = location of the source java code 

    saveImage(imageUrl, destinationFile); 
} 

public static void saveImage(String imageUrl, String destinationFile) throws IOException { 
    URL url = new URL(imageUrl); 

    byte[] b = new byte[2048]; 
    int length; 

    try { 
     InputStream is=url.openStream(); 
      OutputStream os = new FileOutputStream(destinationFile); 
      while ((length = is.read(b)) != -1) { 
       os.write(b, 0, length); 
      } 
      is.close(); 
      os.close(); 
     } 
    }catch (UnknownHostException e){ 
     e.printStackTrace(); 
    } 
} 
+3

'ImageIO.read(URL)','ImageIO的。寫(文件)'... *「希望代碼將此圖像保存在Java代碼的位置」* - 好的,這很難,您可以將它保存在當前執行環境或程序的「工作目錄」中,使用「System .getProperty(「user.dir」)' – MadProgrammer

+0

非常感謝MadProgrammer –

回答

0
String destinationFile = "E:\\Picture\\Wallpaper.jpg"; 

這是直尋址。您可以使用相對尋址

例如在這裏使用:

String destinationFile = "Wallpaper.jpg"; 

在Wallpaper.jpg,並在同一文件夾中的java文件只是保存圖像

+0

非常感謝Reza。我想在另一個班級中使用這個圖像。也許幫助我:我如何解決這個形象?或者我如何使用這個圖像? –

0

有幾種方法可以做到這一點:

  1. 將文件保存在當前目錄或相對於當前目錄的路徑中
  2. 將目錄的路徑保存在屬性文件,屬性文件在類路徑
  3. 是定義一個系統屬性
  4. 傳遞路徑作爲參數
  5. 等...