我需要下载文件,并可能在断开连接后下载零件。尝试下载已经完全下载的文件时出现错误。尝试获取输入流时,我从服务器获取416错误代码。我通过添加条件downloadedFileSize 是否可以使用url连接api处理这些情况?不是通过添加条件try {
File file = Path.of(downloadOutputFolder, fileName).toFile();
boolean append = false;
connection = (HttpURLConnection) url.openConnection();
if (file.exists()) {
connection.setRequestProperty("Range", String.format("bytes=%s-", file.length()));
append = true;
}
if (!file.exists() || file.exists() && file.length() < getFileSizeFromUrl(url)) {
try (InputStream downloadStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file, append)) {
int byteRead;
byte[] buffer = new byte[BUFFER_SIZE];
while ((byteRead = downloadStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, byteRead);
}
}
}...
private int getFileSizeFromUrl(URL url) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
return connection.getContentLength();
} catch (IOException e) {
log.error("Error during open URL connection to {}", url, e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
return -1;
}
file.length()<getFileSizeFromUrl(url)
。