Overview
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.
Requirements
- Java Development Kit (JDK) version 8 or higher
- A backup folder with read and write permissions
Usage
- Download and install the Java Development Kit (JDK) if it is not already installed on your system.
- Create a backup folder on your system with read and write permissions.
- Download the Java program to a directory of your choice. https://github.com/ninniku-it-hub/it-tools/blob/main/BackupFilesClean.class
- Open a terminal or command prompt and navigate to the directory where the program is saved.
- Run the program by entering the command
java(replace “/path/to/backup/folder/” with the actual path to your backup folder).BackupFilesClean/path/to/backup/folder/
Program Steps
- Use the Java Path class to navigate to the backup folder specified by the user.
- Use the Java Files class to retrieve a list of all files in the folder.
- Use the Java Collections class to sort the files by creation date in descending order.
- Create a new folder called “Archive” if it does not already exist.
- Loop through the files in the backup folder and copy the most recent files to the Archive folder.
- Once the number of files in the Archive folder exceeds a certain threshold (e.g. 128GB), delete the oldest files in the folder.
Notes
- 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
javawith args.BackupFilesClean - 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:
https://github.com/ninniku-it-hub/it-tools/blob/main/BackupFilesClean.java
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");
return;
}
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()) {
destDir.mkdir();
}
// 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 {
@SuppressWarnings("resource")
FileChannel srcChannel = new FileInputStream(file).getChannel();
@SuppressWarnings("resource")
FileChannel destChannel = new FileOutputStream(new File(destDir, file.getName())).getChannel();
destChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close();
destChannel.close();
System.out.println(file.getName() + " was copied");
counter++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
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");
return;
}
// 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");
return;
}
// 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
e.printStackTrace();
}
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;
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
size += attrs.size();
return FileVisitResult.CONTINUE;
}
@Override
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
English Version
Overview
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.
Requirements
- Java Development Kit (JDK) version 8 or higher
- A backup folder with read and write permissions
Usage
- Download and install the Java Development Kit (JDK) if it is not already installed on your system.
- Create a backup folder on your system with read and write permissions.
- Download the Java program to a directory of your choice. https://github.com/ninniku-it-hub/it-tools/blob/main/BackupFilesClean.class
- Open a terminal or command prompt and navigate to the directory where the program is saved.
- Run the program by entering the command
java(replace “/path/to/backup/folder/” with the actual path to your backup folder).BackupFilesClean/path/to/backup/folder/
Program Steps
- Use the Java Path class to navigate to the backup folder specified by the user.
- Use the Java Files class to retrieve a list of all files in the folder.
- Use the Java Collections class to sort the files by creation date in descending order.
- Create a new folder called “Archive” if it does not already exist.
- Loop through the files in the backup folder and copy the most recent files to the Archive folder.
- Once the number of files in the Archive folder exceeds a certain threshold (e.g. 128GB), delete the oldest files in the folder.
Notes
- 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
javawith args.BackupFilesClean - 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:
https://github.com/ninniku-it-hub/it-tools/blob/main/BackupFilesClean.java
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");
return;
}
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()) {
destDir.mkdir();
}
// 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 {
@SuppressWarnings("resource")
FileChannel srcChannel = new FileInputStream(file).getChannel();
@SuppressWarnings("resource")
FileChannel destChannel = new FileOutputStream(new File(destDir, file.getName())).getChannel();
destChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close();
destChannel.close();
System.out.println(file.getName() + " was copied");
counter++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
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");
return;
}
// 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");
return;
}
// 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
e.printStackTrace();
}
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;
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
size += attrs.size();
return FileVisitResult.CONTINUE;
}
@Override
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
日本語版
概要
このJavaプログラムは、バックアップフォルダ内の最新ファイルを自動的にバックアップし、最も古いファイルをクリーンアップするために設計されています。このプログラムは、フォルダへの移動にJava Pathクラスを、ファイルの作成と操作にJava Filesクラスを、日付によるファイルのソートにJava Collectionsクラスを使用します。
要件
- Java Development Kit (JDK) バージョン8以上
- 読み取りおよび書き込み権限を持つバックアップフォルダ
使い方
- システムにJava Development Kit (JDK)がまだインストールされていない場合は、ダウンロードしてインストールしてください。
- システム上に読み取りおよび書き込み権限を持つバックアップフォルダを作成してください。
- お好みのディレクトリにJavaプログラムをダウンロードしてください。 https://github.com/ninniku-it-hub/it-tools/blob/main/BackupFilesClean.class
- ターミナルまたはコマンドプロンプトを開き、プログラムが保存されているディレクトリに移動してください。
- コマンド
javaを入力してプログラムを実行してください(「/path/to/backup/folder/」を実際のバックアップフォルダのパスに置き換えてください)。BackupFilesClean/path/to/backup/folder/
プログラムの手順
- Java Pathクラスを使用して、ユーザーが指定したバックアップフォルダに移動します。
- Java Filesクラスを使用して、フォルダ内のすべてのファイルのリストを取得します。
- Java Collectionsクラスを使用して、作成日の降順でファイルをソートします。
- 「Archive」という名前の新しいフォルダがまだ存在しない場合は作成します。
- バックアップフォルダ内のファイルをループし、最新のファイルをArchiveフォルダにコピーします。
- Archiveフォルダ内のファイルが一定のしきい値(例:128GB)を超えた場合、フォルダ内の最も古いファイルを削除します。
注意事項
- デフォルトでは、プログラムは24時間前からの最新ファイルをバックアップし、Archiveフォルダが128GBを超えるとファイルを削除します。これらの値は
javaに引数を付けて実行することで調整できます。BackupFilesClean - フォルダの容量に制限を追加したい場合は、Javaプログラム「BackupFilesClean」を実行する際に追加のパラメータを指定できます。パラメータは以下の通りです:ソースディレクトリ、宛先ディレクトリ、容量(GB単位)。
ソースコード:
https://github.com/ninniku-it-hub/it-tools/blob/main/BackupFilesClean.java
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");
return;
}
String sourceFolder = args[0];
String destFolder = args[1];
File sourceDir = new File(sourceFolder);
File destDir = new File(destFolder);
backupFiles(sourceDir, destDir);
cleanupFolder(destDir, sizeLimit);
}
// カットオフ時間を24時間前に設定
private static void backupFiles(File sourceDir, File destDir) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -24);
Date cutoffDate = cal.getTime();
// 宛先フォルダが存在しない場合は作成
if (!destDir.exists()) {
destDir.mkdir();
}
// ソースフォルダ内のすべてのファイルを取得
File[] files = sourceDir.listFiles();
int counter = 0;
// ソースフォルダから宛先フォルダに過去24時間以内に作成されたファイルをコピー
for (File file : files) {
if (file.isFile() && file.lastModified() >= cutoffDate.getTime()) {
try {
@SuppressWarnings("resource")
FileChannel srcChannel = new FileInputStream(file).getChannel();
@SuppressWarnings("resource")
FileChannel destChannel = new FileOutputStream(new File(destDir, file.getName())).getChannel();
destChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close();
destChannel.close();
System.out.println(file.getName() + " was copied");
counter++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
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; // フォルダの最大サイズ(バイト単位)
// フォルダが存在し、ディレクトリであるか確認
File folder = destDir;
if (!folder.exists() || !folder.isDirectory()) {
System.out.println("Folder does not exist or is not a directory");
return;
}
// フォルダ内のすべてのファイルを取得し、最終更新日時でソート
File[] files = folder.listFiles();
if (files == null || files.length == 0) {
System.out.println("Folder is empty");
return;
}
// フォルダサイズを計算し、サイズ制限以下になるまで最も古いファイルを削除
long folderSize = 0;
try {
folderSize = calculateFolderSize(Paths.get(destDir.getPath()));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Folder size: " + folderSize + " bytes");
// フォルダが最大サイズを超えている場合、最も古いファイルを削除
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;
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
size += attrs.size();
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
// ファイル訪問失敗の処理
return FileVisitResult.CONTINUE;
}
public long getSize() {
return size;
}
}
}実行コマンドと結果
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
