The write()
function in java appends new data to end of file. Here is my question; how the java knows end of file?
- By reading whole file 开发者_Go百科to find end of file
- It knows where the end of file
Which one? Thanks in advance
Many operating systems have a specific file open mode where writes always write to the end of the file. Java may use this to append data to the end of the file.
For example, the manual page for the open()
kernel API function can accept the O_APPEND
flag:
O_APPEND append on each write
Opening a file with O_APPEND set causes each write on the file to be
appended to the end.
Another way to write to the end of the file is to first lseek()
to the end of the file using the SEEK_END
subfunction (see the lseek(2)
man page). New writes to the file will appear at the position of the current file pointer.
However, the lseek()
method can cause two different writers to overwrite each other's data if they try to write to the same offset. For this reason, files such as log files are usually opened using the first method. There's never any reason to write data to a log file anywhere else than the end.
Java will move to the end of the file and append
See http://download.java.net/jdk7/docs/api/java/nio/channels/SeekableByteChannel.html#write(java.nio.ByteBuffer)
or
http://download.oracle.com/javase/tutorial/essential/io/rafs.html
for more info :)
For Unix / Linux at least, the answer is that the operating system takes care of this. Java just makes use of the operating system provided file descriptor that keeps track of the application's current position within the file.
If you opened the file normally (append == false), then a
write
writes data at the file descriptor's current position, and then updates it to point to the position immediately after the data just written.If you opened the file in append mode (append == true), then each
write
writes data at the current end of file.
Note that other Unix / Linux I/O operations use and update the current position of a file descriptor; e.g. read
, seek
and tell
.
Here is my question; how the java knows end of file?
By reading whole file to find end of file: No
It knows where the end of file: Not exactly. It is typically the operating system that knows, not Java.
精彩评论