user1082932
user1082932

Reputation: 11

File operation in Java

I have file reader object in Java.

When we load the file in, is entire file loaded or only file pointer will be loaded like in C. Because I have application (producer) wherein it keeps on writing to the file and other application (consumer) will start to read the file after few minutes, I want to read all file data which will be written by the application producer.

I tried to search but could not get the answer.

Upvotes: 1

Views: 313

Answers (3)

cHao
cHao

Reputation: 86575

A FileReader works a lot like a FileInputStream, which in turn works a lot like its C analogue -- when you first open a file, very little data will actually be loaded immediately. The file's contents generally aren't read in til you first read some of it, at which point the runtime reads enough to fill the request, or the buffer if you're using a BufferedReader (possibly plus enough to fill up a block, depending on the OS and JVM).

When i say it "works like its C analogue", though, i mean it. A FileReader is opened for reading, and a FileWriter is opened for writing. There could be issues with having a file open for reading and writing at the same time. Windows, in particular, isn't too fond of it. If you care about portability, you may want to find another way -- alphazero's answer sounds promising, but i've never tried it.

Upvotes: 1

alphazero
alphazero

Reputation: 27244

Best and canonical approach would be to use Java NIO memory mapped files. Use MappedByteBuffer.force() on each write to insure the consumer process flushes the dirty page files. Consumers (in other process if necessary) can map the same file in read mode.

Upvotes: 1

Paul
Paul

Reputation: 20091

I don't understand what you mean when you wrote, "when we load the file in". Sample code would be helpful here. Please see How to Ask.

If you've called anything that sounds like "read" on your Reader then you've got data in memory. If this is text data (assuming you're using FileReader) then you're better off using a BufferedReader. Not only is it buffered, it's more convenient for text files.

If I have the answer all wrong then please post some code so I know what you're talking about. And welcome!

Upvotes: 0

Related Questions