使用FileChannel和RandonAccessFile重写文件时的附加字符

时间:2016-02-28 21:47:02

标签: java file read-write randomaccessfile filechannel

我尝试使用randonAccessFile和FileChannel替换大文本文件中的现有文本。

这就是我现在所拥有的

public void updateText(final long position, final String newData) throws IOException {
        RandomAccessFile file = new RandomAccessFile(pathToFile, "rw");
        FileChannel inChannel = file.getChannel();
        System.out.println(newData.getBytes().length);
        ByteBuffer buf = ByteBuffer.allocate(newData.length());
        buf.clear();
        buf.put(newData.getBytes());
        buf.flip();
        inChannel.position(position);
        while(buf.hasRemaining()) {
            inChannel.write(buf);
        }
        inChannel.close();
        file.close();
        buf.clear();
    }

我在调用方法时传递这些值

 StringBuffer sb = new StringBuffer();
 sb.append("Java is cold");
 sb.append(System.getProperty("line.separator"));
 sb.append("Good job");
 updateText(14, sb.toString());



 **Input**                 **Expected Output**        **Current output**
What is this?             What is this?                What is this?
Java is cool              Java is cold                 Java is cold
Good old                  Good job                     Good jobb
Jack and Jill             Jack and Jill                Jack and Jill

为什么我最后会获得额外的角色 jobb ?我用相同数量的字符替换文本。我错过了什么?

感谢您的时间。

0 个答案:

没有答案