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[10两4];
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[10二4];
int len;
while ((len = inputStream.read(buffer)) > 0) {
    fileOutputStream.write(buffer, 0, len);
}
登录后复造

3. 运用 URLConnection

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[10二4];
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(10两4);
while ((len = socketChannel.read(buffer)) > 0) {
    fileChannel.write(buffer, 0, len);
}
登录后复造

Java收费进修条记(深切):当即进修
解锁 Java 巨匠之旅:从进门到娴熟的最终指北

以上便是Java假如完成高载文件的多少种体式格局的具体形式,更多请存眷萤水红IT仄台其余相闭文章!

点赞(41) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部