Since you do not explicitly lock the entire file before the copy action, the os file locking mechanism by default works.
I ran a quick test program to find out what happens on a Windows machine when you copy the source file and the external process writes to the file every 2 seconds.
A process that writes to a file has never encountered a problem.
public static void main(String[] args) { File f = new File("..\\test.txt"); long startTime = System.currentTimeMillis(); long elapsedTime = 0; while (elapsedTime < 1000 * 60) { try { FileUtils.writeStringToFile(f, System.currentTimeMillis()+" : Data Write\r\n", true); Thread.sleep(2000); } catch (IOException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex){ Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } elapsedTime = System.currentTimeMillis() - startTime; } }
The process that copies the file throws an exception if it does not complete the copy before the source file changes its length. This exception seems to be more of a warning that the copied version of the file is incomplete. When I synchronized the time so as not to read from the file, at the same time, writing occurs, this exception was not selected.
public static void main(String[] args) { File f = new File("..\\test.txt"); long startTime = System.currentTimeMillis(); long elapsedTime = 0; while (elapsedTime < 1000 * 60) { try { FileUtils.copyFile(f, new File("..\\test\\test.txt")); Thread.sleep(2000); } catch (IOException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex){ Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } elapsedTime = System.currentTimeMillis() - startTime; } }
Based on this test, I would not worry about what happens with the writing process. I would do something to handle the case when java.io.IOException: Failed to copy full contents from '..\test.txt' to '..\test\test.txt' is thrown java.io.IOException: Failed to copy full contents from '..\test.txt' to '..\test\test.txt' .
kfaerber
source share