从URL下载文件时出错

时间:2021-06-12 09:55:43

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

我试图从URL读取文件并使其成为文件类型。

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输出错误= new FileOutputStream(file);

Kindly tell me how can I make File of my url

请告诉我如何制作我的网址文件

2 个解决方案

#1


0  

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>");

精细。而不是File file = new File(“image.png”);使用文件的绝对路径。像File file = new File(“ ”);

#2


0  

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( ) + ">"
); 

#1


0  

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>");

精细。而不是File file = new File(“image.png”);使用文件的绝对路径。像File file = new File(“ ”);

#2


0  

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( ) + ">"
);