用java写一个下载文件的代码
时间: 2023-05-12 11:04:37 浏览: 57
JAVA编写的文件下载代码
好的,以下是一个使用 Java 编写的下载文件的代码示例:
```java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class DownloadFile {
public static void main(String[] args) {
String fileUrl = "https://example.com/file.pdf";
String saveDir = "/path/to/save/directory/";
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
String fileName = conn.getHeaderField("Content-Disposition");
if (fileName == null) {
fileName = url.getFile();
} else {
fileName = fileName.replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1");
}
FileOutputStream outputStream = new FileOutputStream(saveDir + fileName);
byte[] buffer = new byte[4096];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded successfully.");
} catch (Exception e) {
System.out.println("Error while downloading file: " + e.getMessage());
}
}
}
```
这个代码可以从指定的 URL 下载文件,并将其保存到指定的目录中。你可以将 `fileUrl` 和 `saveDir` 替换为你需要的 URL 和目录路径。
阅读全文