寫在前面: 我是 「揚帆向海」,這個昵稱來源于我的名字以及女朋友的名字,我熱愛技術、熱愛開源、熱愛編程,
技術是開源的、知識是共享的,
這博客是對自己學習的一點點總結及記錄,如果您對 Java、演算法 感興趣,可以關注我的動態,我們一起學習,
用知識改變命運,讓我們的家人過上更好的生活,
相關文章: 使用Java以zip形式批量下載檔案、壓縮檔案
文章目錄
- 1. 步驟
- 2. 代碼實作
1. 步驟
- 保證創建一個新檔案
- 創建大小為1024的buffer陣列
- 創建檔案輸出流
- 創建位元組緩沖輸出流
- 檔案逐步寫入本地
5.1 先讀出來保存到buffer陣列中
5.2 然后從 buffer陣列中寫出資料保存到本地- 最后關閉流釋放資源(反向關閉)
2. 代碼實作
/**
* 通過流下載檔案
*
* @param bis res.bodyStream()
* @param filePath 檔案路徑
* @param fileName 檔案名稱
*/
public static void downloadFileByStream(BufferedInputStream bis, String filePath, String fileName) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String fullPath = basePath + sdf.format(new Date()) + File.separator + filePath + File.separator + fileName;
try {
// 1. 保證創建一個新檔案
File file = new File(fullPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file.exists()) {
file.delete();
}
file.createNewFile();
// 2. 創建大小為1024的buffer陣列
byte[] buffer = new byte[1024];
int readLength;
// 3. 創建檔案輸出流,FileOutputStream流以寫入資料到File物件表示的檔案
FileOutputStream fos = new FileOutputStream(new File(fullPath));
// 4. 創建位元組緩沖輸出流
BufferedOutputStream bos = new BufferedOutputStream(fos);
// 5. 檔案逐步寫入本地
// 5.1 先讀出來保存到 buffer陣列中
while ((readLength = bis.read(buffer, 0, 1024)) != -1) {
// 5.2 然后從 buffer陣列中寫出資料保存到本地
bos.write(buffer, 0, readLength);
}
// 6. 最后關閉流釋放資源(反向關閉)
bos.close();
fos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
由于水平有限,本博客難免有不足,懇請各位大佬不吝賜教!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/266700.html
標籤:其他
上一篇:信任即做加法也做減法
下一篇:DSVNP原理以及相關配置
