• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Text search and replacement using nio

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Any updates?
 
Bartender
Posts: 9626
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic