JAVA实现下载两份CSV文件
时间: 2024-01-10 19:03:14 浏览: 24
好的,针对您的问题,我可以提供以下JAVA代码参考:
```
import java.io.*;
import java.net.*;
public class DownloadCSV {
public static void main(String[] args) throws Exception {
// 设置下载链接和保存路径
String url1 = "http://example.com/csv1.csv";
String url2 = "http://example.com/csv2.csv";
String savePath1 = "D:\\csv1.csv";
String savePath2 = "D:\\csv2.csv";
// 下载第一个CSV文件
URL csvUrl1 = new URL(url1);
HttpURLConnection conn1 = (HttpURLConnection) csvUrl1.openConnection();
conn1.setConnectTimeout(5000);
InputStream inputStream1 = conn1.getInputStream();
byte[] getData1 = readInputStream(inputStream1);
// 将第一个CSV文件保存到本地
File file1 = new File(savePath1);
FileOutputStream fos1 = new FileOutputStream(file1);
fos1.write(getData1);
if (fos1 != null) {
fos1.close();
}
if (inputStream1 != null) {
inputStream1.close();
}
// 下载第二个CSV文件
URL csvUrl2 = new URL(url2);
HttpURLConnection conn2 = (HttpURLConnection) csvUrl2.openConnection();
conn2.setConnectTimeout(5000);
InputStream inputStream2 = conn2.getInputStream();
byte[] getData2 = readInputStream(inputStream2);
// 将第二个CSV文件保存到本地
File file2 = new File(savePath2);
FileOutputStream fos2 = new FileOutputStream(file2);
fos2.write(getData2);
if (fos2 != null) {
fos2.close();
}
if (inputStream2 != null) {
inputStream2.close();
}
}
public static byte[] readInputStream(InputStream inputStream) throws Exception {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}
```
使用此代码,可以通过指定下载链接和保存路径来下载两份CSV文件。请不要忘记替换`url`和`savePath`的值,以确保代码正常工作。此外,为了确保下载正常运行,需要导入`java.io.*`和`java.net.*`等相关包。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)