溫馨提示×

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

小億
520
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女