java - How to avoid intermittent empty lines when using FileOutputStream with append = false? -
the following code leaves random.txt
file no content:
final random rand = new random(); while (true) { try (fileoutputstream fos = new fileoutputstream("random.txt", false); printwriter pw = new printwriter(fos, true)) { pw.println(rand.nextlong()); } catch (ioexception ioe) { ioe.printstacktrace(); } }
this can verified using tail
:
$ tail -f random.txt 511109499422519327 -4120669548002912852 -6691981558077108749 -3630360891256027458 2917713483009724854 -5999569794311404435 -7616466037397807657 6997723694593334477 -7350203015863330163 1355067773463270538 -8140835511024500423 -2536681669468724500 -2926317178660145957 -6983787629710676243 7119127016459332336 7186294589323134873 -8389505833590104437 197327637272321424 -1458700265861408851 5685819798785563231 4060059342974359248 215297222019419003 2913123181036087590 -5940005294121482941 5658270253202816998
as can see, there 2 gaps in tail
's output. happens because fileoutputstream(filename, false)
first truncates file, , writes new data it.
so if tail
happens reading content of file right when truncated, shows empty line.
other using techniques involve multiple files, etc. there way make sure truncation , write operations happen atomically?
other using techniques involve multiple files, etc. there way make sure truncation , write operations happen atomically?
no. @ base level, truncation , file write 2 separate syscalls, , os not provide way combine 2 syscalls atomic operation (or transaction).
if intention find edge-case tail -f
have succeeded. otherwise, there better / more efficient ways trying here .... writing pipe, or appending file. , if there particular reason why need this, consider filtering out blank lines.
actually, concerned there worse problem here occasional blank lines. possible losing non-blank lines if java program truncates file before tail
has read last line. (try replacing rand.nextlong()
value of incrementing counter ... , see if see of numbers in tail
output.)
Comments
Post a Comment