java下载文件的方式
Java 提供了多种下载文件的方法。以下是几种常用的方式:
- 使用 URL.openStream()
URL url = new URL("https://example.com/file.txt");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("file.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len);
}登录后复制 - 使用 HttpClient
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://example.com/file.txt");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
FileOutputStream fileOutputStream = new FileOutputStream("file.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len);
}登录后复制 - 使用 URLConnection
立即学习“Java免费学习笔记(深入)”;
URL url = new URL("https://example.com/file.txt");
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("file.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len);
}登录后复制 - 使用 Java NIO
Path path = Paths.get("file.txt");
FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.WRITE);
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("example.com", 80));
ByteBuffer buffer = ByteBuffer.allocate(1024);
while ((len = socketChannel.read(buffer)) > 0) {
fileChannel.write(buffer, 0, len);
}登录后复制以上就是Java如何实现下载文件的几种方式的详细内容,更多请关注php中文网其它相关文章!


MP2 天前
发表在:MagicEXIF通用注册机 v1.13明亮的 旅行分享! 做得真好。
BrendanWaida6 天前
发表在:11日20日,星期四,在这里每天60秒读懂世界!При выборе автономно...
JosephJaf9 天前
发表在:MagicEXIF通用注册机 v1.13我尊重这样的项目, 这里展示真正的旅游。...
Frankcic9 天前
发表在:11日20日,星期四,在这里每天60秒读懂世界!Для блога может быть...
Stevedaf18 天前
发表在:MagicEXIF通用注册机 v1.13所有文章都令人印象深刻。继续保持 真诚。...
Stevedaf19 天前
发表在:Intel XTU中文补丁 1.13我经常访问 关于旅行的资源。有趣阅读游记...
Stevedaf19 天前
发表在:MagicEXIF通用注册机 v1.13我常常想, 能像你们一样多旅行。感谢激励...
Stevedaf19 天前
发表在:Intel XTU中文补丁 1.13很高兴阅读 有用的内容。十分 很有意思。...
Stevedaf19 天前
发表在:MagicEXIF通用注册机 v1.13我早就想, 能像你们一样多旅行。谢谢启发...
Stevedaf19 天前
发表在:Intel XTU中文补丁 1.13我一直梦想, 那么放松地度假。感谢激励。...