1. 程式人生 > 實用技巧 >一行程式碼實現位元組陣列寫入磁碟生成檔案

一行程式碼實現位元組陣列寫入磁碟生成檔案

前言:請各大網友尊重本人原創知識分享,謹記本人部落格:南國以南i

今天我們來使用一個極其簡單的操作檔案工具類,使用apache當中commons下的檔案工具類FileUtils,使用它能大大的簡化我們對檔案的操作。

1.匯入FileUtils的依賴

1  <!-- FileUtils依賴-->
2         <dependency>
3             <groupId>commons-io</groupId>
4             <artifactId>commons-io</artifactId>
5
<version>2.4</version> 6 </dependency>

2.引入io包使用FileUtils類生成一張gif圖片到磁碟中

1  //獲取網上資源圖片,下載到本地磁碟
2     @RequestMapping("/dowload")
3     public void dowload()throws Exception{
4         InputStream in = new URL("http://www.baidu.com/img/baidu_logo.gif").openStream();
5         byte
[] gif = IOUtils.toByteArray(in); //將檔案轉換位元組陣列 6 String outpath = "E:\\test.gif"; 7 FileUtils.writeByteArrayToFile(new File(outpath),gif);//匯出路徑檔案格式,位元組陣列 8 }

結果說明:可以看出E盤根目錄下生成了test.gif這麼一個檔案,測試通過!!!

3.使用FileUtils檔案工具類生成MP3格式音訊檔案

說明:此處音訊位元組陣列是從redis中獲取,請關注上篇文章:將音訊檔案轉二進位制分包儲存到Redis(奇淫技巧操作)

 1    /**
 2      * 從redis中分包取值進行byte[]數組合並解析音訊
 3      */
 4     @RequestMapping("/getkeyAudio")
 5     public void getKey(HttpServletResponse response) throws Exception{
 6         OutputStream os = response.getOutputStream();
 7         List list =redisTemplate.opsForList().range("Audio", 0, -1); //通過key獲取指定區間的值,List方式儲存用List集合去接收
 8 
 9         //合併音訊位元組陣列
10         List<byte[]> blist = list;
11         int lengthTotal = 0;
12         for (byte[] item : blist) {
13             lengthTotal += item.length;
14         }
15         byte[] totalByte = new byte[lengthTotal];
16         int begin = 0;
17         for (byte[] item : blist) {
18             //System.arraycopy(原陣列, 原陣列起始位置, 目標陣列, 目標陣列起始位置, 複製長度);
19             System.arraycopy(item, 0, totalByte, begin, item.length);
20             begin += item.length;
21         }
22 
23         String outfile = "E:\\Audio.mp3";
24         FileUtils.writeByteArrayToFile(new File(outfile),totalByte);//匯出路徑檔案格式,位元組陣列
25 
26     }

結果:再次回到E盤,效果和我預期的一致生成了MP3格式的音訊檔案(可以正常播放的哈!)

個人總結:

我是南國以南i記錄點滴每天成長一點點,學習是永無止境的!轉載請附原文連結!!!