A piece of Java code that automatically cleans up system temporary files regularly

/**
	 * Clean up the files with the specified prefix in the system temporary directory.
	 * @param filenamePrefix filename prefix
	 * @param minutes a few minutes to perform a cleanup operation
	 */
	public void cleanTempFile(String filenamePrefix,int minutes) {

		Timer timer = new Timer ();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				String tmpdir = System.getProperty("java.io.tmpdir");
				File dir = new File(tmpdir);
				String arr[] = dir.list();
				if (arr != null) {
					for (String fileName : arr) {
						if (fileName.startsWith("zuul-servo-metrics")) {
							deleteDir(new File(tmpdir + fileName));
						}
					}
				}
			}
			private boolean deleteDir(File dir) {
				try {
					if (dir.isDirectory()) {
						String[] children = dir.list();
						// Recursively delete subdirectories in the directory
						for (int i = 0; i < children.length; i++) {
							boolean success = deleteDir(new File(dir,children[i]));
							if (!success) {
								return false;
							}
						}
					}
					// The directory is empty at this time and can be deleted
					return dir.delete();
				} catch (Exception e) {
					return false;
				}
			}
		}, 0, minutes * 60 * 1000); // execute every 5 minutes
	}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326286659&siteId=291194637