Java を使用して、ハード ドライブ全体のファイルの変更を取得したいと考えています。例 c:\ または /mnt/drives/hdd1
多くの異なるコンピューターが異なるファイル構造で使用され、他のソフトウェアに影響を与えずに簡単に変更できないため、これは要件です。ただし、特定のファイルとファイルタイプはインデックス化する必要があります。ドライブ c:\ d:\ e:\ および任意のサブフォルダーに存在できます。
すべてのサブディレクトリを手動で追加する必要があるため、Java WatchService はその役割を果たしません。実行不可能で遅い 10+k を超えるフォルダーがあります。
私はJAVAでこのようなものを探しています:
C# と Java の実装の違い: WatchService Java コードを管理者権限で実行した場合、c:\$Recycle.Bin にはアクセスできますが、c:\Documents and Settings にはアクセスできません。アクセス拒否例外が発生します。誰かが理由を教えてもらえますか? そして、私が述べたように、すべてのサブディレクトリがクロールされるまで多くの時間がかかるため、WatchService は解決策ではありません。フォルダ。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileSystemWatcherTest
{
class Program
{
static void Main(string[] args)
{
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
try
{
// Watch for changes on this path
fileSystemWatcher.Path = "c:\\";
// Watch for changes on all files
fileSystemWatcher.Filter = "*.*";
// Also watch for changes within sub directories
fileSystemWatcher.IncludeSubdirectories = true;
fileSystemWatcher.Changed += fileSystemWatcher_Changed;
fileSystemWatcher.Created += fileSystemWatcher_Created;
fileSystemWatcher.Deleted += fileSystemWatcher_Deleted;
fileSystemWatcher.Renamed += fileSystemWatcher_Renamed;
// Begin watching
fileSystemWatcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
while (true)
{
System.Threading.Thread.Sleep(60 * 1000);
}
}
static void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine("Rename " + e.FullPath);
}
static void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("Delete " + e.FullPath);
}
static void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("Create " + e.FullPath);
}
static void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("Change " + e.FullPath);
}
}
}
JAVA 実装:
private void registerDirectoryWithSubfolders(final Path start) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException
{
System.out.println(dir);
try
{
registerDirectory(dir);
}
catch(java.nio.file.AccessDeniedException ex)
{
System.err.println("Access Denied: " + dir);
}
catch(java.lang.Throwable ex)
{
System.err.println("Exception: " + dir);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException
{
System.err.println("Error And SKIP " + file);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return FileVisitResult.SKIP_SUBTREE;
}
});
}