java下载另一个服务器的http地址文件
时间: 2024-02-06 08:04:21 浏览: 25
以下是使用Java下载另一个服务器的HTTP地址文件的示例代码:
```
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DownloadFile {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt"; // Replace with the URL of the file to download
String savePath = "C:/Downloads/file.txt"; // Replace with the local path to save the downloaded file
try {
URL url = new URL(fileUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
Path saveFilePath = Paths.get(savePath);
Files.copy(inputStream, saveFilePath);
System.out.println("File downloaded successfully.");
} else {
System.out.println("HTTP response code: " + responseCode);
}
httpConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:在运行此代码之前,请确保您的Java程序可以访问所需的URL。如果需要,您可能需要设置代理服务器或防火墙规则。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)