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下載文件的方式,可以根據具體的需求選擇合適的方法。