I have to use the file as the database , But I am confused that how to insert the data into file . It is very stupid that copy the file and add the new data then rewrite a new file. And I notice that many database have store the data into the file and they both write in C/C++ . And I wonder how to achieve same function in Java. But I had try many times , use RandomAccessFile and FileChannel to insert the data . But it just overwrite the data at the position i want to insert .Some inspire idea will be help! Thanks :)!
Here is code I had ever write.But it overwrite ! overwrite!
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Reader {
public static void main(String[] args) throws IOException {
new File("a.txt").createNewFile();
FileChannel fc = FileChannel.open(Paths.get("a.txt"),StandardOpenOption.WRITE);
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put("one\ntwo\nthree\nfour\n".getBytes());
buf.flip();
fc.write(buf);
//set the pos to insert the data
//I want to insert the data after three the pos is 14
fc.position(14);
//clear the buf and add the new data
buf.clear();
buf.put("five\n".getBytes());
buf.flip();
fc.write(buf);
fc.close();
}
}