java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
java.net.URL(args[1].toString()).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("WorldEdit/schematics/"+args[2].toString());
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte data[] = new byte[1024];
while(in.read(data,0,1024)>=0)
{
bout.write(data);
}
bout.close();
in.close();
}
我希望它从网址下载文件,并将其放入文件夹中。该程序将位于名为“plugins”的文件夹中,我想将下载的文件放在“plugins/WorldEdit/schematic”中。 似乎不起作用。有什么建议么?
最佳答案
in.read
返回一个数字,指示实际读取了多少字节。您忽略该数字并假设每次调用读取 1024 字节。
如果您使用的是 Java 7,则可以通过以下方式将 URL 保存到文件中:
try (InputStream in = new URL(args[1].toString()).openStream()) {
Files.copy(in, Paths.get("WorldEdit", "schematics", args[2].toString()));
}
在 Java 6(以及 5 和 4)中,您可以使用 channel :
FileChannel fileChannel = fos.getChannel();
ReadableByteChannel urlChannel = Channels.newChannel(
new URL(args[1].toString()).openStream());
fileChannel.transferFrom(urlChannel, 0, Long.MAX_VALUE);
关于java - 从 URL 下载文件到文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16948249/