2014-04-05 60 views
0

我想創建一個程序,將資源從網頁下載到文件中。我創建了一個mkir函數,該函數創建一個名稱爲給定String的哈希的十六進制版本的目錄。然後,我創建了一個saveResource函數,該函數將資源保存在文件中以及字節數組中。然而,當我嘗試節約資源到該文件中,我得到一個錯誤信息,指出:java.io.FileNotFoundException:648451a1(是一個目錄)mkdir在java中的功能

這裏的功能是:

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; 

     } 
     } 
+1

'FileOutputStream fout = new FileOutputStream(dir)'看起來可疑,因爲你看到的錯誤。 – vanza

回答

1

的錯誤是簡單因爲你不能在目錄中寫入數據。

嘗試打印dir.isDirectory()以確認它是否是目錄。由於它的參數部分,請檢查調用方法。