0

I'm trying to replace existing text from a large text file using randonAccessFile and FileChannel.

This is what I have right now

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

I'm passing these values while invoking the method

 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

Why am I getting additional character at the end jobb? I'm replacing the text with same number of characters. What am I missing?

Thank you for your time.

user1799214
  • 511
  • 2
  • 11
  • 25

0 Answers0