what is the difference between file and random access file?
R – the difference between file and random access file
file-accessrandom-access
Related Solutions
java.io.RandomAccessFile is the class you're looking for. Here's an example implementation (you'll probably want to write some unit tests, as I haven't :)
package test;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Raf {
private static class Record{
private final double price;
private final int id;
private final int stock;
public Record(int id, int stock, double price){
this.id = id;
this.stock = stock;
this.price = price;
}
public void pack(int n, int offset, byte[] array){
array[offset + 0] = (byte)(n & 0xff);
array[offset + 1] = (byte)((n >> 8) & 0xff);
array[offset + 2] = (byte)((n >> 16) & 0xff);
array[offset + 3] = (byte)((n >> 24) & 0xff);
}
public void pack(double n, int offset, byte[] array){
long bytes = Double.doubleToRawLongBits(n);
pack((int) (bytes & 0xffffffff), offset, array);
pack((int) ((bytes >> 32) & 0xffffffff), offset + 4, array);
}
public byte[] getBytes() {
byte[] record = new byte[16];
pack(id, 0, record);
pack(stock, 4, record);
pack(price, 8, record);
return record;
}
}
private static final int RECORD_SIZE = 16;
private static final int N_RECORDS = 1024;
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile(args[0], "rw");
try{
raf.seek(RECORD_SIZE * N_RECORDS);
raf.seek(0);
raf.write(new Record(1001, 476, 28.35).getBytes());
raf.write(new Record(1002, 240, 32.56).getBytes());
} finally {
raf.close();
}
}
}
Just an update of the HTML5 features is in http://www.html5rocks.com/en/tutorials/file/dndfiles/. This excellent article will explain in detail the local file access in JavaScript. Summary from the mentioned article:
The specification provides several interfaces for accessing files from a 'local' filesystem:
- File - an individual file; provides readonly information such as name, file size, MIME type, and a reference to the file handle.
- FileList - an array-like sequence of File objects. (Think
<input type="file" multiple>
or dragging a directory of files from the desktop). - Blob - Allows for slicing a file into byte ranges.
See Paul D. Waite's comment below.
Best Solution
A random access file is a file where you can "jump" to anywhere within it without having to read sequentially until the position you are interested in.
For example, say you have a 1MB file, and you are interested in 5 bytes that start after 100k of data. A random access file will allow you to "jump" to the 100k-th position in one operation. A non-random access file will require you to read 100k bytes first, and only then read the data you're interested in.
Hope that helps.
Clarification: this description is language-agnostic and does not relate to any specific file wrapper in any specific language/framework.