生成一段下载文件java代码
时间: 2023-03-14 12:42:56 浏览: 47
要下载文件,您可以使用Java代码来实现:URL url = new URL("url");
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();// 检查响应码
if (responseCode == HttpURLConnection.HTTP_OK) {
// 如果响应码是OK,则表示可以下载文件
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength(); if (disposition != null) {
// 检索文件名
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
// 从URL中检索文件名
fileName = url.getFile();
} System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName); // 读取文件输入流
InputStream inputStream = httpConn.getInputStream(); // 打开文件输出流
FileOutputStream outputStream = new FileOutputStream(fileName); int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
} outputStream.close();
inputStream.close(); System.out.println("文件已下载");
} else {
System.out.println("无法下载文件,响应码:" + responseCode);
}
httpConn.disconnect();