在Java中将行添加到文件中

fol*_*one 21 java file-io

有没有办法在Java中添加一行到文件,而不创建临时文件,并将所需内容写入其中?

Ste*_*n C 21

不,没有办法在Java 中安全地做到这一点.

任何主流操作系统中的文件系统实现都不支持此类事情,并且您不会在任何主流编程语言中找到此功能.

真实世界文件系统在将数据存储为固定大小的"块"的设备上实现.无法实现文件系统模型,您可以在其中将字节插入文件中间,而不会显着减慢文件I/O,浪费磁盘空间或两者兼而有之.


涉及文件就地重写的解决方案本质上是不安全的.如果您的应用程序在前置/重写过程中被终止或电源耗尽,则可能会丢失数据.我不建议在实践中使用这种方法.

使用临时文件.它更安全.


sfu*_*ger 6

有一种方法,它涉及重写整个文件(但没有临时文件).正如其他人提到的,没有文件系统支持将内容预先添加到文件中.下面是一些示例代码,它使用RandomAccessFile写入和读取内容,同时保留一些缓冲在内存中的内容:

public static void main(final String args[]) throws Exception {
    File f = File.createTempFile(Main.class.getName(), "tmp");
    f.deleteOnExit();

    System.out.println(f.getPath());

    // put some dummy content into our file
    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
    for (int i = 0; i < 1000; i++) {
        w.write(UUID.randomUUID().toString());
        w.write('\n');
    }
    w.flush();
    w.close();

            // append "some uuids" to our file
    int bufLength = 4096;
    byte[] appendBuf = "some uuids\n".getBytes();
    byte[] writeBuf = appendBuf;
    byte[] readBuf = new byte[bufLength];

    int writeBytes = writeBuf.length;

    RandomAccessFile rw = new RandomAccessFile(f, "rw");
    int read = 0;
    int write = 0;

    while (true) {
                    // seek to read position and read content into read buffer
        rw.seek(read);
        int bytesRead = rw.read(readBuf, 0, readBuf.length);

                    // seek to write position and write content from write buffer
        rw.seek(write);
        rw.write(writeBuf, 0, writeBytes);

                    // no bytes read - end of file reached
        if (bytesRead < 0) {
                            // end of
            break;
        }

                    // update seek positions for write and read
        read += bytesRead;
        write += writeBytes;
        writeBytes = bytesRead;

                    // reuse buffer, create new one to replace (short) append buf
        byte[] nextWrite = writeBuf == appendBuf ? new byte[bufLength] : writeBuf;
        writeBuf = readBuf;
        readBuf = nextWrite;
    };

    rw.close();

            // now show the content of our file
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
}
Run Code Online (Sandbox Code Playgroud)