简体   繁体   English

错误而从下载网址文件

[英]Error while downloading a file from url

I am trying to read a file from url and making it a File Type. 我正在尝试从url读取文件并使其成为File类型。

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); 但是我在OutputStream output = new FileOutputStream (file);时遇到错误OutputStream output = new FileOutputStream (file);

Kindly tell me how can I make File of my url 请告诉我如何制作我的url File

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"); 而不是File file = new File ("image.png"); use absolute path for the file. 使用文件的绝对路径。 Like File file = new File ("<absolute-path-from-root-directory>"); File file = new File ("<absolute-path-from-root-directory>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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