ssummeraw 2013-06-06 09:41 采纳率: 10%
浏览 2498

从 url 中下载文件时的错误

我想从url中读取一个文件,然后定义它为一个File Type

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); 处出错了。
请问如何定义 URl 中的文件?

  • 写回答

2条回答 默认 最新

  • 码密码密哄 2013-06-06 10:01
    关注
       /**
         * Constructs a new file using the specified path.
         *
         * @param path
         *            the path to be used for the file.
         */
        public File(String path) {
            this.path = fixSlashes(path);
        }
    

    这是File的构造方法,你那是找不到文件的 path应该是绝对路径

    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建