I am trying to identify if a print job or a .prn file has been completed being written to the computer. Steps to create : Click print on a file -> and select (print to file) The file will be attempted to save on a location on your computer and a window to enter the file name and save the location will be opened. Enter the name of the file and click save.
The file will then start writing to the specified folder as a .prn file. I am trying to accomplish identifying if this writing has been complete and if the file is available for further processing. How to identify if the file is complete and ready in java ? I tried the file lock (nio) and also the random file access. The latter worked, when trying to save/move/copy from one location on the computer to the other, but when I tried to save using .prn, this failed.
Please suggest on identifying if a .prn file writing is complete in java.
Below is the code I have tried to achieve to find out if the .prn file has completed writing to folder. I have tried this, from this link here.
public void uploadFiles(final File folder) {
if (folder.list().length > 0) {
upload.setEnabled(true);
for (final File fileEntry : folder.listFiles()) {
try {
if(isFileCompletelyWritten(fileEntry)){
if (onSendData(fileEntry.getAbsolutePath())) {
deleteFile(fileEntry);
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
} else {
upload.setEnabled(false);
}
}
private boolean isFileCompletelyWritten(File file) {
RandomAccessFile stream = null;
try {
stream = new RandomAccessFile(file, "rwd");
return true;
} catch (Exception e) {
System.out.println("Skipping file " + file.getName() + " for this iteration as it's not completely written");
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
System.out.println("Exception during closing file " + file.getName());
}
}
}
return false;
}
The
isFileCompletelyWritten(File file)
method is what I added to find if the file writing is complete. This did not work whenI tried to save the print file, but it did work while copying, moving, saving the files from one folder on the computer to the other. The .prn file was available to my program as and when the byte stream came in. Rather than skip the file, the RandomfileAccess was not able to detect if the writing was complete or not. When the byte stream wrote the file sequentially chunk by chunk, my program, proceeded further with its next steps, thinking the file is complete and available. When I ran the same code while copying a file on the local from one location to the other, the Randomfileaccess was able to check and see that more data is being written, and my program was able to skip the process for that iteration. This is how my program failed.