前言:请各大网友尊重本人原创知识分享,谨记本人博客:南国以南i
今天我们来使用一个极其简单的操作文件工具类,使用apache当中commons下的文件工具类FileUtils,使用它能大大的简化我们对文件的操作。
1.导入FileUtils的依赖
1 23 commons-io 4commons-io 52.4 6
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记录点滴每天成长一点点,学习是永无止境的!转载请附原文链接!!!