原标题: 在Java中,可以使用`URL`和`URLConnection`类来下载文件到本地。以下是一个基本示例:
导读:
```javaimport java.io.BufferedInputStream;import java.io.FileOutputStream;import java.io...
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void main(String[] args) throws IOException {
String fileUrl = "";
String savePath = "/path/to/save/file.pdf";
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream out = new FileOutputStream(savePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
System.out.println("File downloaded successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个程序将从给定的URL下载文件,并保存到指定的路径,确保替换 `fileUrl` 和 `savePath` 变量为你自己需要的实际值。