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
会译·对照式翻译
会译是一款AI智能翻译浏览器插件,支持多语种对照式翻译
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如何实现下载文件的几种方式的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/527951.html
微信扫一扫
支付宝扫一扫