我在dropbox上有一个公共文件存储,现在我想使用java下载该文件。这是我做的:
String url = "http://www.dropbox.com/s/vk67dz9ca0oqz37/Chrysanthemum.jpg";
String filename = "C:\\Users\\Public\\Pictures\\Sample Pictures\\test.jpg";
try {
URL download = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(download.openStream());
FileOutputStream fileOut = new FileOutputStream(filename);
fileOut.getChannel().transferFrom(rbc, 0, 1 << 24);
fileOut.flush();
fileOut.close();
rbc.close();
} catch (Exception e) {
e.printStackTrace();
}
但是test.jpg
是无效的。怎么了?
当你点击保管箱页“下载原”,你可以看到它您重定向到http小号://www.dropbox.com/s/vk67dz9ca0oqz37/Chrysanthemum.jpg?dl = 1
因此,请附加?dl=1
到您的网址并使用https
。
String url = "https://www.dropbox.com/s/vk67dz9ca0oqz37/Chrysanthemum.jpg?dl=1";
String filename = "C:\\Users\\Public\\Pictures\\Sample Pictures\\test.jpg";
try {
URL download = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(download.openStream());
FileOutputStream fileOut = new FileOutputStream(filename);
fileOut.getChannel().transferFrom(rbc, 0, 1 << 24);
fileOut.flush();
fileOut.close();
rbc.close();
} catch (Exception e) {
e.printStackTrace();
}
或者,更短:
String url = "https://www.dropbox.com/s/vk67dz9ca0oqz37/Chrysanthemum.jpg?dl=1";
String filename = "C:\\Users\\Public\\Pictures\\Sample Pictures\\test.jpg";
try {
URL download = new URL(url);
Path fileOut = new File(filename).toPath();
Files.copy(download.openStream(), fileOut, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句