前言:請各大網友尊重本人原創知識分享,謹記本人博客:南國以南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記錄點滴每天成長一點點,學習是永無止境的!轉載請附原文鏈接!!!