【问题标题】:mkdir function in javajava中的mkdir函数
【发布时间】:2014-04-05 02:35:39
【问题描述】:

我正在尝试创建一个程序,将网页中的资源下载到文件中。我创建了一个 mkir 函数,该函数创建一个目录,其名称是给定字符串哈希的十六进制版本。然后,我创建了一个 saveResource 函数,将资源保存在文件和字节数组中。但是,当我尝试将资源保存到文件中时,我收到一条错误消息:java.io.FileNotFoundException: 648451a1 (Is a directory)

函数如下:

 public static File mkdir(String s) throws IOException
   {
      String dirname = s;
      s = Integer.toHexString(dirname.hashCode());
      File directory = new File(s);

      if  (!directory.exists() && !directory.mkdir())
         throw new IOException("can't make directory for " + s);

      return directory;
   }

public static byte[] saveResource(File dir, String urlString, 
                      String argURLString)
      throws IOException, URISyntaxException
   {
      URL u = new URL(urlString);
      URLConnection uc = u.openConnection();
      urlString = uc.getContentType();
      int contentLength = uc.getContentLength();

      try (InputStream raw = uc.getInputStream()) {
          InputStream in = new BufferedInputStream(raw);

          byte[] data = new byte[contentLength];
          int offset = 0;
          while (offset < contentLength) {
              int bytesRead = in.read(data, offset, data.length - offset);
              if (bytesRead == -1) break;
              offset += bytesRead;
      }
          if (offset != contentLength) {
              throw new IOException("Only read " + offset
                        + " bytes; Expected " + contentLength + " bytes");
          }
          urlString = u.getFile();
          urlString = urlString.substring(urlString.lastIndexOf('/') + 1);
          try (FileOutputStream fout = new FileOutputStream(dir)) {
              fout.write(data);
              fout.flush();
          }
          return data;

      }
      }

【问题讨论】:

  • 鉴于您看到的错误,FileOutputStream fout = new FileOutputStream(dir) 看起来很可疑。

标签: java web-crawler mkdir


【解决方案1】:

这个错误很简单,因为你不能在目录中写入数据。

尝试打印dir.isDirectory() 以确认它是否是目录。由于它是参数的一部分,请检查调用者方法。

【讨论】:

    猜你喜欢
    • 2012-05-11
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 2023-03-04
    • 2014-06-19
    • 2012-02-06
    • 2013-03-06
    • 2013-04-21
    相关资源
    最近更新 更多