This Java program is designed to automatically back up the most recent files and clean up the oldest files in a backup folder. The program uses the Java Path class to navigate to the folder, the Java Files class to create and manipulate files, and the Java Collections class to sort files by date.


  • Java Development Kit (JDK) version 8 or higher
  • A backup folder with read and write permissions


  1. Download and install the Java Development Kit (JDK) if it is not already installed on your system.
  2. Create a backup folder on your system with read and write permissions.
  3. Download the Java program to a directory of your choice. https://github.com/ninniku-it-hub/it-tools/blob/main/BackupFilesClean.class
  4. Open a terminal or command prompt and navigate to the directory where the program is saved.
  5. Run the program by entering the command java BackupFilesClean /path/to/backup/folder/ (replace “/path/to/backup/folder/” with the actual path to your backup folder).

Program Steps

  1. Use the Java Path class to navigate to the backup folder specified by the user.
  2. Use the Java Files class to retrieve a list of all files in the folder.
  3. Use the Java Collections class to sort the files by creation date in descending order.
  4. Create a new folder called “Archive” if it does not already exist.
  5. Loop through the files in the backup folder and copy the most recent files to the Archive folder.
  6. Once the number of files in the Archive folder exceeds a certain threshold (e.g. 128GB), delete the oldest files in the folder.


  • By default, the program will back up the recent files from 24 hours ago and delete files in the Archive folder once it exceeds 128GB. These values can be adjusted by executing java BackupFilesClean with args.
  • If you want to add a limit to the capacity of the folder, you can add an additional parameter when running the Java program “BackupFilesClean”. The parameters are as follows: source directory, destination directory, and capacity (in GB).

Source code:


import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;

public class BackupFilesClean {
	public static void main(String[] args) {
		long sizeLimit = 128;
		if (args.length >= 2) {
			System.out.println("Source folder path: " + args[0]);
			System.out.println("Destination folder path: " + args[1]);
			if (args.length >= 3 && args[2] != null) {
				sizeLimit = Long.valueOf(args[2]);
			System.out.println("Folder size limit: " + sizeLimit + " GB");
		} else {
			System.out.println("No parameters specified");

		String sourceFolder = args[0];
		String destFolder = args[1];
		File sourceDir = new File(sourceFolder);
		File destDir = new File(destFolder);
		backupFiles(sourceDir, destDir);
		cleanupFolder(destDir, sizeLimit);

	private static void backupFiles(File sourceDir, File destDir) {
		// Set cutoff time to 24 hours ago
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, -24);
		Date cutoffDate = cal.getTime();

		// Create destination folder if it does not exist
		if (!destDir.exists()) {

		// Get all files in the source folder
		File[] files = sourceDir.listFiles();
		int counter = 0;
		// Copy files created in the last 24 hours from source folder to destination
		// folder

		for (File file : files) {
			if (file.isFile() && file.lastModified() >= cutoffDate.getTime()) {
				try {
					FileChannel srcChannel = new FileInputStream(file).getChannel();
					FileChannel destChannel = new FileOutputStream(new File(destDir, file.getName())).getChannel();
					destChannel.transferFrom(srcChannel, 0, srcChannel.size());
					System.out.println(file.getName() + " was copied");
				} catch (IOException e) {
		System.out.println("Backup completed. " + counter + " file(s) were successfully copied.");


	private static void cleanupFolder(File destDir, long sizeLimit) {

		long maxFolderSize = sizeLimit * 1024L * 1024L * 1024L; // Maximum folder size in bytes
		// Check if folder exists and is a directory
		File folder = destDir;
		if (!folder.exists() || !folder.isDirectory()) {
			System.out.println("Folder does not exist or is not a directory");

		// Get all files in folder and sort by last modified time
		File[] files = folder.listFiles();
		if (files == null || files.length == 0) {
			System.out.println("Folder is empty");

		// Calculate folder size and delete oldest files until folder size is under size
		// limit
		long folderSize = 0;
		try {
			folderSize = calculateFolderSize(Paths.get(destDir.getPath()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
		System.out.println("Folder size: " + folderSize + " bytes");

		// Delete the oldest file if the folder exceeds the maximum size
		while (folderSize > maxFolderSize) {
			Arrays.sort(files, Comparator.comparingLong(File::lastModified));
			File oldestFile = files[0];

			Path path = Paths.get(oldestFile.getPath());
			try {
				long fileSize = Files.size(path);
				System.out.println("File size: " + fileSize + " bytes");
				if (oldestFile.delete()) {
					folderSize -= fileSize;
					System.out.println("Deleted file: " + oldestFile.getName());
				} else {
					System.out.println("Failed to delete file: " + oldestFile.getName());
			} catch (IOException e) {
				System.err.println("Failed to get file size: " + e.getMessage());

	public static long calculateFolderSize(Path folderPath) throws IOException {
		FolderSizeVisitor visitor = new FolderSizeVisitor();
		Files.walkFileTree(folderPath, visitor);
		return visitor.getSize();

	private static class FolderSizeVisitor extends SimpleFileVisitor<Path> {
		private long size = 0;

		public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
			size += attrs.size();
			return FileVisitResult.CONTINUE;

		public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
			// Handle file visit failure
			return FileVisitResult.CONTINUE;

		public long getSize() {
			return size;

Execution command and results.

java BackupFilesClean /tmp/src /tmp/dst 10
Source folder path: /tmp/src
Destination folder path: /tmp/dst
Folder size limit: 10 GB
test_backup.txt was copied
Backup completed. 1 file(s) were successfully copied.
Folder size: 11 bytes

By Ray Lee (System Analyst)

iDempeire ERP Contributor, 經濟部中小企業處財務管理顧問 李寶瑞

Leave a Reply

Your email address will not be published. Required fields are marked *