Java下载文件的方式有以下几种:
URL url = new URL(fileUrl);
InputStream in = url.openStream();
OutputStream out = new FileOutputStream(savePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
out.close();
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(fileUrl);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream in = entity.getContent();
OutputStream out = new FileOutputStream(savePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
out.close();
}
response.close();
httpClient.close();
ReadableByteChannel inChannel = Channels.newChannel(new URL(fileUrl).openStream());
FileOutputStream out = new FileOutputStream(savePath);
FileChannel outChannel = out.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
while (inChannel.read(buffer) != -1) {
buffer.flip();
outChannel.write(buffer);
buffer.clear();
}
inChannel.close();
outChannel.close();
out.close();
以上是几种常见的Java下载文件的方式,可以根据具体的需求选择合适的方法。