Предоставьте журнал, если два файла идентичны и имеют одинаковое содержимое в Java - PullRequest
2 голосов
/ 24 января 2020

У меня есть код ниже, где я читаю файл из определенного каталога, обрабатываю его и после обработки я перемещаю файл в каталог архива. Это работает нормально. Я получаю новый файл каждый день и использую задание планировщика Control-M для запуска этого процесса.

Теперь при следующем запуске я снова читаю новый файл из этого конкретного каталога и проверяю этот файл с файлом в архивный каталог и, если содержимое отличается, то только обработать файл, иначе ничего не делать. Для этой работы написан сценарий оболочки, и мы не видим никакого журнала для этого процесса.

Теперь я хочу создать сообщение журнала в моем коде java, если файлы идентичны из определенного каталога и в затем запустите директорию архива, чтобы «файлы были идентичны» Но я не знаю точно, как это сделать. Я не хочу писать логи c для обработки или перемещения чего-либо в файле. Мне просто нужно проверить, равны ли файлы и, если это так, создать сообщение журнала. Файл, который я получаю, не очень большой, и максимальный размер может быть до 10 МБ.

Ниже мой код:

        for(Path inputFile : pathsToProcess) {
            // read in the file:
            readFile(inputFile.toAbsolutePath().toString());
            // move the file away into the archive:
            Path archiveDir = Paths.get(applicationContext.getEnvironment().getProperty(".archive.dir"));
            Files.move(inputFile, archiveDir.resolve(inputFile.getFileName()),StandardCopyOption.REPLACE_EXISTING);
        }
        return true;
    }

    private void readFile(String inputFile) throws IOException, FileNotFoundException {
        log.info("Import " + inputFile);

        try (InputStream is = new FileInputStream(inputFile);
                Reader underlyingReader = inputFile.endsWith("gz")
                        ? new InputStreamReader(new GZIPInputStream(is), DEFAULT_CHARSET)
                        : new InputStreamReader(is, DEFAULT_CHARSET);
                BufferedReader reader = new BufferedReader(underlyingReader)) {

            if (isPxFile(inputFile)) {
                Importer.processField(reader, tablenameFromFilename(inputFile));
            } else {
                Importer.processFile(reader, tablenameFromFilename(inputFile)); 
            }

        }
        log.info("Import Complete");
    }       

}

1 Ответ

1 голос
/ 24 января 2020

На основании ограниченной информации о размере файла или потребностях в производительности можно сделать что-то подобное. Это может быть не на 100% оптимизировано, а просто пример. Возможно, вам также придется выполнить некоторую обработку исключений в методе main, поскольку новый метод может вызвать IOException:

import org.apache.commons.io.FileUtils;  // Add this import statement at the top


// Moved this statement outside the for loop, as it seems there is no need to fetch the archive directory path multiple times.
Path archiveDir = Paths.get(applicationContext.getEnvironment().getProperty("betl..archive.dir"));  

for(Path inputFile : pathsToProcess) {

    // Added this code
    if(checkIfFileMatches(inputFile, archiveDir); {
        // Add the logger here.
    }
    //Added the else condition, so that if the files do not match, only then you read, process in DB and move the file over to the archive. 
    else {
        // read in the file:
        readFile(inputFile.toAbsolutePath().toString());
        Files.move(inputFile, archiveDir.resolve(inputFile.getFileName()),StandardCopyOption.REPLACE_EXISTING);
    }       
}


//Added this method to check if the source file and the target file contents are same.
// This will need an import of the FileUtils class. You may change the approach to use any other utility file, or read the data byte by byte and compare. If the files are very large, probably better to use Buffered file reader.
    private boolean checkIfFileMatches(Path sourceFilePath, Path targetDirectoryPath) throws IOException {
        if (sourceFilePath != null) {  // may not need this check
            File sourceFile = sourceFilePath.toFile();
            String fileName = sourceFile.getName();

            File targetFile = new File(targetDirectoryPath + "/" + fileName);

            if (targetFile.exists()) {
                return FileUtils.contentEquals(sourceFile, targetFile);
            }
        }
        return false;
    }
...