2017-02-17 26 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. 等...