0

I'm using Stream to read a particular line from file and with the help of pre-calculated Byte position value I'm using FileChannel and ByteBuffer to write to same location in a big file. Basically editing some values in textFile.

//Read a particular line

Stream<String> lines = Files.lines(Paths.get('PATHTOFILE'));
String text = lines.skip(LINENUMBER).findFirst().get();

// Modify text for example

text.replace("R",r); 

// Re-Write to same position after manipulating the same text

RandomAccessFile file = new RandomAccessFile('PATHTOFILE', "rw");
FileChannel channel= file.getChannel();
ByteBuffer buf = ByteBuffer.allocate(50);
buf.put(text)
buf.flip()
channel.position(PRE_CALCULATED_POSITION);
while(buf.hasRemaining)
   channel.write(buf)
channel.close(); buf.clear(); file.close();

I'm wondering if there a cleaner or much better way to do the same without reading line by line?

Thanks

user1799214
  • 511
  • 2
  • 11
  • 25

0 Answers0