简体   繁体   中英

Error while downloading a file from url

I am trying to read a file from url and making it a File Type.

Below is the code

public File fileFromUrl(String str) throws IOException
      {
          File file = new File ("image.png");
          URL url = new URL (str);
            InputStream input = url.openConnection().getInputStream();
            try {

                OutputStream output = new FileOutputStream (file);
                try {
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                        output.write(buffer, 0, bytesRead);
                    }
                } finally {
                    output.close();
                }
            } finally {
                input.close();
            }
          return file;
      }

However I am experiencing error at OutputStream output = new FileOutputStream (file);

Kindly tell me how can I make File of my url

It would be helpful if you have posted the exception that you are getting, but my guess is that you don't have write permissions to the current working directory in which you are trying to create your output file.

If you want to see where it tries to write the file, add this diagnostic to your program:

System.out.println(
  "Absolute path of image.png: <" + file.getAbsolutePath( ) + ">"
); 

Fine. Instead of File file = new File ("image.png"); use absolute path for the file. Like File file = new File ("<absolute-path-from-root-directory>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM