Reading file using Java

H

Hyden Zeng

Hi all,
got one question regarding file reading.
How do I directly access a certain byte or line of a file using Java?
the time complexity should be O(1).
Thank you.
 
G

Gordon Beaton

How do I directly access a certain byte or line of a file using
Java? the time complexity should be O(1).

Open the file using a RandomAccessFile. Use seek() to get to the
desired location. Use an appropriate read method from that class to
get the data.

/gordon
 
M

Marco Schmidt

Hyden Zeng:
got one question regarding file reading.
How do I directly access a certain byte or line of a file using Java?
the time complexity should be O(1).

You can access a certain byte by skipping over data with InputStream
or calling the seek method with RandomAccessFile. The complexity
should be O(1). However, extensions of InputStream that do not
override the default implementation of skip(long) will read every byte
before the position you want to go to, so no more O(1) there.

As for accessing a certain line - that's not possible in O(1) without
having some index file which stores the offsets of all lines in a text
file.

Regards,
Marco
 
M

Michael Borgwardt

Hyden said:
Hi all,
got one question regarding file reading.
How do I directly access a certain byte or line of a file using Java?
the time complexity should be O(1).

To access a byte address, you can use java.io.RandomAccessFile, there's
probably also an alternative in java.nio

Accessing a certain line in O(1) is fundamentally impossible unless
either line lengths are fixed (in which case a simple computation
reduces it to the earlier problem) or you have a precomputed index
that maps line numbers to byte offsets.
 
A

Andrew Thompson

| Hi all,
| got one question regarding file reading.
| How do I directly access a certain byte

RandomAcessFile

|..or line of a file using Java?

If it's FCW, use the formula ((LineNo-1)*LineWidth)
to calculate which byte the line corresponds to,
then RAF.

Otherwise, the best you could do on a non-FCW
file is a binary search, unless you are prepared to
trawl throught he file once, and creat a second
(much smaller) FCW 'index file' for the larger file.

| ..the time complexity should be O(1).

In a perfect world, yes. (I am just guessing
what O(1) means)

| Thank you.

You're welcome..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top