java对文件的处理,遍历、下载、删除、移动等

APP上线良好,后台管理网站需要一个记录每天app运行日志的功能,有专门代码人员查看日志有哪些崩溃的地方,具体需求如下:

1、将服务器上文件夹里的日志文件显示到页面上,点击下载可通过浏览器将日志文件下载至本地进行查看。

注:为了安全考虑,需要减少对真实日志文件的操作,所以另外新建一个文件夹,将日志文件复制到新的文件夹下进行操作。

2、每天凌晨00:01分,将上一天的日志文件,复制到新的文件夹下,并且删除新文件夹下前6天的日志文件,一般来说,那些日志文件已经查看,没作用了,为了节省空间(洁癖)。

一、将磁盘的文件显示到页面上

 1 /**
 2      * 运行日志列表
 3      * 
 4      * @user Anear
 5      * @time 17:24
 6      */
 7     @RequestMapping("/getCatalinaLog")
 8     public String getCatalinaLog(AppUserLog appUserLog, String pageNo,
 9             HttpServletRequest request, HttpServletResponse response,ModelMap model) {
10         List<LogLife> logNameList = new ArrayList<LogLife>();
11         String filePath = "E:/log_file";//待修改路径  日志文件夹路径
12         File f = new File(filePath);
13         if (!f.exists()) {
14             System.out.println(filePath + " not exists");
15             return "appUser/catalinaLog";
16         }
17         
18         File fa[] = f.listFiles();
19         
20         
21         /* for (File file : fa) {
22             life.setLogName(file.getName());
23             logNameList.add(life);
24         }*/
25         
26         for (int i = 0; i < fa.length; i++) {
27             LogLife life = new LogLife();
28             life.setLogName("");
29             File fs = fa[i];
30             if (fs.isDirectory()) {
31             //    System.out.println(fs.getName() + " [目录]");
32             } else {
33             //    System.out.println(fs.getName());
34                 life.setLogName(fs.getName());
35                 life.setUrl(fs.getName());
36                 logNameList.add(life);
37             }
38         }
39         PageList<LogLife> lPageList = new PageList<LogLife>();
40         lPageList.setRecords(logNameList);
41 
42         model.put("logName", logNameList);
43         model.put("pageList", lPageList);
44         model.put("appUserLog", appUserLog);
45         return "appUser/catalinaLog";
46     }
1 public class LogLife {
2     private String logName;//文件名称   
3     private String url;// 请求的路径  
4     private String filePath;//文件将要保存的目录
5     private String method;//方法 post or get
6

 

 

 

二、将显示的日志下载到本地

 1 /**
 2      * 下载日志
 3      * https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png
 4      * @throws IOException 
 5      * @user Anear
 6      * @time 17:24
 7      */
 8     @RequestMapping("/downloadingLog")
 9     public void downloadingLog(AppUserLog appUserLog,String fileName_downLoad, String pageNo,
10             HttpServletRequest request, HttpServletResponse response,ModelMap model) throws IOException {
11         //String apkPath=YmWebAppConfig.getSYSTEM_FILE_SOURSE().concat(YmWebAppConfig.getUpdateAppAndroidDir()).concat("/"+appInfo.getApkName());
12         String apkPath = "E:/log_file"+"/"+fileName_downLoad;//待修改路径  指定日志文件路径 下载
13         File apk=new File(apkPath);
14         if(apk.exists() && apk.isFile()){
15             String fileName=apk.getName();
16             response.reset();  
17             response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
18             response.addHeader("Content-Length", "" + apk.length());  
19             response.setContentType("application/octet-stream;charset=UTF-8");  
20             InputStream inputStream=new FileInputStream(apk);
21             byte[] b=new byte[inputStream.available()];
22             inputStream.read(b);
23             OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
24             outputStream.write(b);  
25             outputStream.flush();  
26             outputStream.close();
27             inputStream.close();
28         }else{
29             LogUtil.errorLog("浏览器下载,找不到源文件", log);
30         }
31     }

三、定时将服务器的日志文件,复制到新的文件夹下,并且删除6天前的废弃日志

1 <!-- 开启任务注解扫描 -->
2       <task:annotation-driven/>
3       <bean id="autoTransTask" class="com.***.***.controller.AutoTransImpl"/>
4       <task:scheduled-tasks>
5           <task:scheduled ref="autoTransTask" method="executeAutoTrans" cron="0 01 00 * * *"/>
6       </task:scheduled-tasks>
 1 /**
 2  * FileName:    AutoTransImpl
 3  * Author:      Anear
 4  * Date:        2017/5/7
 5  * Description: 定时操作运行日志
 6  */
 7 @Component("AutoTrans")
 8 public class AutoTransImpl implements AutoTrans {
 9 
10     @Override
11     @Transactional(propagation = Propagation.REQUIRES_NEW)
12     public void executeAutoTrans() {
13         File directory = null;
14         Calendar cal = Calendar.getInstance();
15         SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
16         
17         Object obj = "E:/oldlog"+"/";//老目标文件夹下所有文件 //待修改路径  指定日志文件路径
18         String url = "E:/newlog"+"/";
19         
20         String cal2 = getCalendar(1);
21     //    System.out.println("前一天时间:"+cal2);
22           
23         if (obj instanceof File) {  
24             directory = (File) obj;  
25         } else {  
26             directory = new File(obj.toString());  
27         }  
28         ArrayList<File> files = new ArrayList<File>();  
29         if (directory.isFile()) {  
30             files.add(directory);  
31         } else if (directory.isDirectory()) {  
32             File[] fileArr = directory.listFiles(); 
33             for (File file : fileArr) {
34                 long time = file.lastModified();          
35                 cal.setTimeInMillis(time);  
36                 System.out.println(formatter.format(cal.getTime()));
37                 if (formatter.format(cal.getTime()).equals(cal2)) {//如果文件修改时间为前一天
38                     String oldPath = obj.toString()+file.getName(); //"D:/apache-tomcat-7.0.79/logs/localhost_access_log.2017-09-11.txt";
39                     String newPath = url+file.getName();
40                 //    System.out.println("oldPath:"+oldPath+",,,,,newPath:"+newPath);
41                     try { 
42                            int bytesum = 0; 
43                            int byteread = 0; 
44                            File oldfile = new File(oldPath); 
45                            if (oldfile.exists()) {                  //文件存在时 
46                                InputStream inStream = new FileInputStream(oldPath);      //读入原文件 
47                                FileOutputStream fs = new FileOutputStream(newPath); 
48                                byte[] buffer = new byte[1444]; 
49                                int length;
50                                while ( (byteread = inStream.read(buffer)) != -1) { 
51                                    bytesum += byteread;            //字节数 文件大小 
52                      //              System.out.println(bytesum); 
53                                    fs.write(buffer, 0, byteread); 
54                                } 
55                                inStream.close();
56                            } 
57                        }  catch (Exception e) { 
58                            System.out.println("复制单个文件操作出错"); 
59                            e.printStackTrace(); 
60                        } 
61                 }
62             }
63         }
64         cal2 = getCalendar(6);
65         directory =new File(url+"info.log."+cal2);
66         if (directory.exists()) {//删除
67             directory.delete();
68         }
69            
70         
71     }
72     //获取日期
73     public String getCalendar(int num){
74         SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
75         Calendar cal = Calendar.getInstance();
76         int day = cal.get(Calendar.DATE);  //当前时间的前一天
77         
78         cal.set(Calendar.DATE, day-num);
79    //     System.out.println(formatter.format(cal.getTime()));
80         return formatter.format(cal.getTime());
81     }
82 }

 

posted @ 2017-12-22 17:39  根目录97  阅读(1625)  评论(0编辑  收藏  举报