This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Text search and replacement using nio  RSS feed

 
Esha Goel
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I want to search a particular text ina file and replace it with a different string (much more in length).

I am tryinh it with regular expression and new io.

here is my code snippet

.....................................
RandomAccessFile raf=new RandomAccessFile(f,"rw");
FileChannel fc = raf.getChannel();
int len=(int)fc.size();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_WRITE, 0, len);

Charset charset = Charset.forName("US-ASCII");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer cb = decoder.decode(bb);

Pattern p = Pattern.compile("texttomatch");
Matcher m = p.matcher(cb); // get a matcher object
StringBuffer sb = new StringBuffer();
byte[] src=null;

while (m.find()) {
m.appendReplacement(sb, "texttoreplace with");
///src=new String(cb.array()).getBytes();
///writeBuffer.put(src);

//bb.put(sb.toString().getBytes());

}

m.appendTail(sb);

bb.force();
//raf.close();
fc.close();
.....................................


When i see the string buffer the text is correctly replace but i am not able to put it in mapped buffer.

If anybody has some solution or some better way ,then please let me know
 
Esha Goel
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any updates?
 
Joe Ess
Bartender
Posts: 9428
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the JavaRanch.
Unfortunately NIO doesn't have a very big user base so your options are often to use the regular IO classes or get reading.
[ February 08, 2008: Message edited by: Joe Ess ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!