• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Text search and replacement using nio  RSS feed

 
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?
 
Bartender
Posts: 9526
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 ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!