java从redis中下载文件到本地-代码记录

常用代码记录

 1     /**
 2      * 从redis中下载文件
 3      * @param originFileName 文件名称
 4      * @param key redis 的key
 5      * @param path 需要下载到什么地方
 6      */
 7     private void downFileForRedis(String originFileName, String key, String path) {
 8         byte[] bytesForRedis = (byte[]) RedisUtil.getObjectValue(key);
 9 
10         File downFileDir = getFileObj(path);
11         if (downFileDir.listFiles() != null) {
12             for (File file : downFileDir.listFiles()) {
13                 file.delete();
14             }
15         }
16         try (ByteArrayInputStream bis = new ByteArrayInputStream(bytesForRedis);
17              FileOutputStream fileOut = new FileOutputStream(downFileDir.getPath() + File.separatorChar + originFileName);
18              BufferedOutputStream bos = new BufferedOutputStream(fileOut);
19         ) {
20             byte[] buf = new byte[4096];
21             int length = bis.read(buf);
22             //保存文件
23             while (length != -1) {
24                 bos.write(buf, 0, length);
25                 length = bis.read(buf);
26             }
27             RedisUtil.delObjectValue(key);
28         } catch (Exception e) {
29             logger.error("down for redis error", e);
30         }
31     }
32 
33     /**
34      * 获取基于基础路径  @see getBasePath()
35      * 文件夹的对象,如果不存在则创建
36      * @param path
37      * @return
38      */
39     private File getFileObj(String path) {
40         String basePath = getBasePath();
41 
42         File downFileDir = new File(basePath + File.separatorChar + path);
43         if (!downFileDir.exists()) {
44             downFileDir.mkdir();
45 
46         }
47         return downFileDir;
48     }
49 
50 
51     /**
52      * 获取文件存放的基础路径
53      * @return
54      */
55     private String getBasePath() {
56         ApplicationHome h = new ApplicationHome(XXXX.class);
57         File jarF = h.getSource();
58         File parentFile = jarF.getParentFile();
59         File parentParentFile = parentFile.getParentFile();
60         String parentParentPath = parentParentFile.toString();
61         String downDir = "down";
62         String basePath = parentParentPath + File.separatorChar + downDir;
63 
64         File file = new File(basePath);
65         if (!file.exists()) {
66             file.mkdir();
67 
68         }
69         return basePath;
70     }

猜你喜欢

转载自www.cnblogs.com/kuibuqianli/p/12334720.html