【发布时间】: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