Java 文件处理程序:实时监控文件夹并处理新文件
public class FileProcessor { private static String fileNameInMemory = 'file1.txt'; // 内存中存放的文件名
public static void main(String[] args) {
Thread fileCheckThread = new Thread(() -> {
while (true) {
File folder = new File('path/to/folder'); // 本地文件夹路径
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
String fileName = file.getName();
if (!fileName.equals(fileNameInMemory)) {
// 开启新的线程去操作这个文件
Thread fileOperationThread = new Thread(() -> {
System.out.println('New thread is processing file: ' + fileName);
// 执行文件操作的代码
});
fileOperationThread.start();
}
}
}
}
});
fileCheckThread.start();
}
}
while 循环的作用
while 循环的作用是持续监测指定文件夹中是否有新的文件出现。在每次循环中,程序会获取文件夹中的所有文件,并逐个检查文件名是否和内存中的文件名相同。如果发现有新的文件名和内存中的文件名不同,就会启动一个新的线程来处理该文件。循环会一直进行下去,以便实时监测文件夹中是否有新的文件出现。
原文地址: https://www.cveoy.top/t/topic/qs9L 著作权归作者所有。请勿转载和采集!