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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM