Firstly sorry for my english.
I have linux on my machine and have run .jar file here. From java code I input some content in printer-counter.log file. everything works fine even if I shut down machine and and power on it again the content is there perfectly, but if i plug out from electricity and power on again the content of printer-counter.log file is empty.
public <K, V> void update(StoragePair<K, V> pair) throws IOException {
log.debug("start updating counter pair");
Preconditions.checkState(pair.getKey().toString().length() > 0, "Empty key detected!");
Preconditions.checkState(pair.getValue().toString().length() > 0, "Empty value detected!");
Path filePath = file.toPath();
try (FileOutputStream fos = new FileOutputStream(file);
FileChannel fileChannel = fos.getChannel();
FileLock fileLock = fileChannel.lock()) {
// Acquire lock on the file
System.out.println("File is locked");
// Read the file content
StringBuilder buffer = new StringBuilder();
try (Stream<String> filesStream = Files.lines(filePath)) {
buffer.append(
filesStream.filter(f -> !f.split(KEY_VALUE_SEPARATOR)[KEY_INDEX].equals(pair.getKey().toString()))
.sequential()
.collect(Collectors.joining(lineSeparator))
);
}
// Add the new pair to the buffer
addPairToStringBuffer(pair, buffer);
// Backup the original file
File backupFile = FileUtils.getFile(file.getAbsolutePath() + "-backup");
FileUtils.moveFile(FileUtils.getFile(file.getAbsolutePath()), backupFile);
// Write the modified content back to the file
FileUtils.writeStringToFile(file, buffer.toString() + lineSeparator, Charset.defaultCharset(), false);
// Force any buffered data to be written to the disk
fileChannel.force(true);
System.out.println("File lock released");
// Remove the temporary backup file
backupFile.delete();
} catch (IOException e) {
log.error("Error while writing printer counter: " + e);
}
}
I am using the following code to write data in printer-counter.log and it works correctly. i think problem isn’t there in my code. maybe it is Linux’s bug or something (i tried the same thing on linux 64 bit debian 11, 64 bit debian 10 and 32 bit debian 9 and the results were the same: content is empty) help me
Nika Kakauridze is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1