java下载文件的方式
Java 提供了多种下载文件的方法。以下是几种常用的方式:
1. 使用 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);
}2. 使用 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);
}3. 使用 URLConnection
一套面向小企业用户的企业网站程序!功能简单,操作简单。实现了小企业网站的很多实用的功能,如文章新闻模块、图片展示、产品列表以及小型的下载功能,还同时增加了邮件订阅等相应模块。公告,友情链接等这些通用功能本程序也同样都集成了!同时本程序引入了模块功能,只要在系统默认模板上创建模块,可以在任何一个语言环境(或任意风格)的适当位置进行使用!
0
立即学习“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);
}4. 使用 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中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号