0

Hello i am using the File class in java to write a txt file with over 100,000 lines of information. I am on fedora linux. While the file is being written to i don't want it to be allowed to be read until it is fully completed.

I thought setting the setReadable(false) before having the file be written then at the end setting it to true would work but it did not does anyone know how i can do this correctly

Thank you.

user1863457
  • 131
  • 2
  • 11
  • 3
    Maybe this helps: http://stackoverflow.com/questions/128038/how-can-i-lock-a-file-using-java-if-possible – redc0w Jan 30 '13 at 14:29

2 Answers2

1

Write it with a .tmp extension and then move/rename it to the real extension when finished

final File file = new File(filename + ".tmp");

// code to save the text to the file

file.renameTo(new File(filename+ ".txt")) 

The .renameTo is an atomic action on linux.

Gertjan Assies
  • 1,890
  • 13
  • 23
  • renameTo would not be atomic on Windows, see this: http://stackoverflow.com/questions/1000183/reliable-file-renameto-alternative-on-windows – lbalazscs Jan 30 '13 at 14:52
  • @lbalazscs He mentions fedora linux in his question and there it is atomic – Gertjan Assies Jan 30 '13 at 14:54
  • This will not prevent processes from writing to the file. filename+".tmp" is still writable by any process. The Java NIO package has file-locking. – mawcsco Jan 30 '13 at 15:35
1

You should implement that with transactions from Apache. it allows you to write to files in single transaction. Your base file won't even exist before you commit it

But you can also do that alone. Write your file elsewhere and move it when completed

Grooveek
  • 10,046
  • 1
  • 27
  • 37