我想通过以下代码保存图像(从URL)到我的磁盘。我希望代码将此图像保存在Java代码的位置。例如,如果源Java代码在d: example saveimage.java中,则此图像保存在d: example image.jpg中。在安装过程中可以更改此位置。我怎样才能做到这一点?它的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();
}
}
String destinationFile = "E:\Picture\Wallpaper.jpg";
这是一个直接的解决方案。您可以使用相对地址
例如,这里使用:
String destinationFile = "Wallpaper.jpg";
只是将图像保存在wallpaper.jpg中,并将图像保存在与Java文件同一文件夹中
有几种方法:
- 将文件保存在当前目录中或相对于当前目录的路径
- 具有属性文件中目录的路径,属性文件在classPath中
- 定义系统属性
- 作为参数的路径
- 等...