Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用java将数据插入到文件中?无附加_Java_File_Io - Fatal编程技术网

如何用java将数据插入到文件中?无附加

如何用java将数据插入到文件中?无附加,java,file,io,Java,File,Io,我必须使用该文件作为数据库,但我对如何将数据插入该文件感到困惑。复制文件并添加新数据然后重写新文件是非常愚蠢的。我注意到许多数据库都将数据存储到文件中,并且都是用C/C++编写的。我想知道如何在Java中实现同样的功能。但是我尝试了很多次,使用RandomAccessFile和FileChannel插入数据。但它只是覆盖了我想插入的位置的数据。一些启发性的想法会有所帮助! 谢谢:) 这是我曾经写过的代码。但是它覆盖了!覆盖 import java.io.File; import java.io.

我必须使用该文件作为数据库,但我对如何将数据插入该文件感到困惑。复制文件并添加新数据然后重写新文件是非常愚蠢的。我注意到许多数据库都将数据存储到文件中,并且都是用C/C++编写的。我想知道如何在Java中实现同样的功能。但是我尝试了很多次,使用RandomAccessFile和FileChannel插入数据。但它只是覆盖了我想插入的位置的数据。一些启发性的想法会有所帮助! 谢谢:)

这是我曾经写过的代码。但是它覆盖了!覆盖

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

    }
}

不能插入文件中间。C/C++也不能做到这一点

要插入文件中间,必须移动文件内容的其余部分,为新数据腾出空间。

你必须这样做。没有内置的API,甚至在C/C++中也没有


<>数据库的数据文件是复杂的,即使它们不在文件中间插入新的数据。

没有简单的方法在文件的中间“插入”一行。文件系统和I/O子系统不是这样工作的。要真正插入一行,您必须复制文件,并在复制时将该行添加到正确的位置

你说“……许多数据库都将数据存储到文件中……”——这是真的,但他们使用复杂的块级技术来实现,在磁盘上维护块链,并更新指针,使其看起来像插入了行。要使所有这些对数据库用户透明,需要做大量工作


编写一个简单的“数据库”,可以在文件中间插入数据,这是一项非常重要的工作。

这有助于:我想把数据插入到文件中的任何一行中。他们的数据是通过B树维护的吗?我真的很难用B-树来维护文件中的数据。。。数据库的数据文件是复杂的。这超出了本文的讨论范围,尤其是考虑到每个数据库的处理方式都不同。我将尝试另一种方法来实现相同的功能。谢谢。