|
50鱼币
如题;
比如说:
(随便举个例子)
Test.txt 文件存在内容:
Hello World!
写入内容为 name
预期效果为:
name
Hello World!
现有的类好像都没有办法。
先读取数据,操作数据,然后写入。
网上提供了的方法。
- 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[20];
- 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();
- }
复制代码
|
最佳答案
查看完整内容
现有的类好像都没有办法。
先读取数据,操作数据,然后写入。
网上提供了的方法。
调用insert("test.txt", 0, "中国".getBytes());
另一个方法,使用的类不同。
|