Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将图像(从url)保存到java代码位置_Java - Fatal编程技术网

将图像(从url)保存到java代码位置

将图像(从url)保存到java代码位置,java,Java,我想通过下面的代码将图像(从url)保存到我的磁盘。 我希望代码将此图像保存在java代码的位置。例如,如果源java代码位于D:\example\saveimage.java中,则此图像将保存在D:\example\image.jpg中。此位置可能在安装过程中更改。 我该怎么做?它的java代码是什么? 多谢各位 public static void main(String[] args) throws Exception { String imageUrl ="http://imgs

我想通过下面的代码将图像(从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 = "Wallpaper.jpg";

只需将图像保存在Wallpaper.jpg中,并与java文件保存在同一文件夹中即可。有几种方法可以做到这一点:

  • 将文件保存在当前目录中,或保存到相对于当前目录的路径
  • 在属性文件中具有目录的路径,属性文件位于类路径中
  • 定义系统属性
  • 将路径作为参数传递
  • 等等

  • ImageIO.read(URL)
    ImageIO.write(File)
    …*“希望代码将此图像保存在java代码的位置”*-好的,这更难,您可以使用
    System.getProperty(“user.dir”)
    非常感谢MadProgrammervery感谢Reza将其保存在程序的当前执行上下文或“工作目录”中。我想在另一个类中使用此图像。也许可以帮助我:我怎样才能对这张图片进行寻址?或者如何使用此图像?
    String destinationFile = "Wallpaper.jpg";