温馨提示×

java中怎么下载文件流保存到本地

小亿
172
2023-09-04 21:36:40
栏目: 编程语言

在Java中,可以使用InputStreamOutputStream来下载文件流并保存到本地。

下面的代码演示了如何使用URLURLConnection来获取文件流,并使用FileOutputStream将其保存到本地文件中:

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.zip"; // 要下载的文件URL
String savePath = "C:/path/to/save/file.zip"; // 要保存的文件路径
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("文件下载完成。");
} catch (Exception e) {
e.printStackTrace();
}
}
}

在上面的代码中,fileUrl是要下载的文件的URL,savePath是要保存文件的本地路径。程序使用URL创建一个连接,然后通过URLConnection获取文件的输入流。接下来,我们使用FileOutputStream创建一个输出流,将文件流写入到本地文件中。最后,关闭输入流和输出流。

需要注意的是,上述代码是在主线程中执行的,如果需要在后台线程中执行文件下载操作,可以将代码放在一个RunnableThread中运行。

0