-1

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();

    }
}
Jason Long
  • 79
  • 1
  • 12

2 Answers2

2

There is no simple way to "insert" a line in the middle of a file. Filesystems and I/O subsystems don't work that way. To truly insert a line you have to copy the file and add the line in the right place as you are copying.

You say "...many database have store the data into the file ..." -- this is true, but they do it with sophisticated block-level techniques where they maintain chains of blocks on disk and update pointers to make it look like the rows are inserted. A lot of work goes into making all this transparent to the database user.

Writing even a simple "database" that can insert data in the middle of a file is a significant amount of work.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
1

You cannot insert in the middle of a file. C/C++ cannot do that either.

To insert in the middle of a file, the rest of the file content has to be moved, to make room for the new data.

You have to do such a move. There is no built-in API for that, not even in C/C++.

The data files of a database are complex, and even they don't insert new data in the middle of a file.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Does their data maintain by a B-tree? It is really hard to me to use the B-tree to maintain the data in the file... XC – Jason Long Jul 12 '16 at 02:16
  • The data files of a database are ***COMPLEX***. It is way out of scope to cover that here, especially considering that every database does it differently. – Andreas Jul 12 '16 at 02:17