我正在尝试创建一个程序,将资源从网页下载到文件中。我创建了一个mkir函数,它创建了一个目录,其名称是给定String的哈希值的十六进制版本。然后,我创建了一个saveResource函数,它将资源保存在文件中,也保存在字节数组中。但是,当我尝试将资源保存到文件中时,我收到一条错误消息,指出:java.io.FileNotFoundException:648451a1(是一个目录)
以下是功能:
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;
}
}
答案 0 :(得分:1)
错误很简单,因为您无法在目录中写入数据。
尝试打印dir.isDirectory()
以确认其目录是否正确。由于它是参数的一部分,请检查调用方法。