前言:請各大網友尊重本人原創知識分享,謹記本人博客:南國以南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記錄點滴每天成長一點點,學習是永無止境的!轉載請附原文鏈接!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/125402.html
標籤:Java
下一篇:fwrite(): send of 8192 bytes failed with errno=104 Connection reset by peer
