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中文网其它相关文章!


JosephJaf11 天前
发表在:MagicEXIF通用注册机 v1.13充满正能量的 旅行分享! 感谢激励。 <...
JosephJaf19 天前
发表在:Intel XTU中文补丁 1.13欣赏你的照片, 我感受到, 旅游让人相连...
JosephJaf21 天前
发表在:MagicEXIF通用注册机 v1.13我热爱这样的想法, 那么放松地度假。真的...
BrianSab1 个月前
发表在:南通速强批量添加水印专家 v1.83Эта статья для ознак...
Ronaldgag1 个月前
发表在:11日17日,星期一,在这里每天60秒读懂世界!Free PHP Blockchain ...
NelsonBOT1 个月前
发表在:11日16日,星期日,在这里每天60秒读懂世界!Free non-criminal in...
Darrenjhjhjhcunny1 个月前
发表在:11日14日,星期五,在这里每天60秒读懂世界!Атака черной материи...
parifoot-rdc-791 个月前
发表在:laravel 找不到页面Votre guide <a href=...
Anya142Sa2 个月前
发表在:ASUS华硕A8N-SLI Deluxe主板BIOS 10110Hello friends! I c...
91资源网站长-冰晨2 个月前
发表在:广告合作123