从URL下载文件时出错

时间:2012-09-09 18:30:49

标签: java android eclipse

我正在尝试从网址读取文件并将其设为File类型。

以下是代码

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;
      }

但我在OutputStream output = new FileOutputStream (file);

时遇到错误

请告诉我如何制作File

url

2 个答案:

答案 0 :(得分:0)

如果您发布了正在获取的异常,那将会很有帮助,但我猜测您对当前正在尝试创建输出文件的工作目录没有写入权限。

如果您想查看它尝试写入文件的位置,请将此诊断添加到您的程序中:

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

答案 1 :(得分:0)

精细。而不是File file = new File ("image.png");使用文件的绝对路径。与File file = new File ("<absolute-path-from-root-directory>");

一样
相关问题