一阵三十六 发表于 2022-4-12 15:33:18

Java写入文件时怎样把写入内容写到文件开头?

如题;

比如说:
(随便举个例子)
Test.txt 文件存在内容:
Hello World!

写入内容为 name

预期效果为:
name
Hello World!

ba21 发表于 2022-4-12 15:33:19

现有的类好像都没有办法。
先读取数据,操作数据,然后写入。
网上提供了的方法。
public static void insert(String filename, long offset, byte[] content) throws IOException {
                RandomAccessFile r = new RandomAccessFile(new File(filename), "rw");
                RandomAccessFile rtemp = new RandomAccessFile(new File(filename + "~"), "rw");
               
                long fileSize = r.length();
                FileChannel sourceChannel = r.getChannel();
                FileChannel targetChannel = rtemp.getChannel();

                sourceChannel.transferTo(offset, (fileSize - offset), targetChannel);
                sourceChannel.truncate(offset);
                r.seek(offset);
                r.write(content);

                long newOffset = r.getFilePointer();
                targetChannel.position(0L);
                sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));

                sourceChannel.close();
                targetChannel.close();

        }


调用insert("test.txt", 0, "中国".getBytes());

另一个方法,使用的类不同。

    public void test3() throws IOException {

      RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");

      raf1.seek(3);//将指针调到角标为3的位置
      //保存指针3后面的所有数据到StringBuilder中
      StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
      byte[] buffer = new byte;
      int len;
      while((len = raf1.read(buffer)) != -1){
            builder.append(new String(buffer,0,len)) ;
      }
      //调回指针,写入“xyz”
      raf1.seek(3);
      raf1.write("xyz".getBytes());

      //将StringBuilder中的数据写入到文件中
      raf1.write(builder.toString().getBytes());

      raf1.close();

    }

一阵三十六 发表于 2022-4-12 15:34:33

我只能写成:

Hello World!
name

这样。
页: [1]
查看完整版本: Java写入文件时怎样把写入内容写到文件开头?