java下载的代码实现
时间: 2024-01-01 11:16:04 浏览: 21
以下是使用Java实现文件下载的代码示例:
```java
import java.io.*;
import java.net.*;
public class FileDownloader {
public static void downloadFile(String fileURL, String saveDir) throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
if (disposition != null) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
}
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded successfully");
} else {
System.out.println("File download failed");
}
httpConn.disconnect();
}
public static void main(String[] args) {
String fileURL = "https://www.example.com/file.pdf";
String saveDir = "C:/Downloads";
try {
downloadFile(fileURL, saveDir);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们使用Java中的HttpURLConnection类来建立HTTP连接并下载文件。我们从响应中获取文件名,并将其保存到本地文件系统中。如果下载成功,程序将输出“File downloaded successfully”。