gpt4 book ai didi

java - java中的mkdir函数

转载 作者:行者123 更新时间:2023-12-01 13:10:56 27 4
gpt4 key购买 nike

我正在尝试创建一个程序,将资源从网页下载到文件中。我创建了一个 mkir 函数,该函数创建一个目录,其名称是给定字符串的哈希值的十六进制版本。然后,我创建了一个 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;

}
}

最佳答案

错误很简单,因为您无法在目录中写入数据。

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

关于java - java中的mkdir函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22875913/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com