Computing Magazine

Search And Replace String in ByteBuffer

Posted on the 17 November 2015 by Abhishek Somani @somaniabhi
This is a simple java program which will search and replace a particular String in ByteBuffer

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
public class ByteBufferTest {

public static void main(String[] args)
{
String fullText = "javarootsbestwebsiteoftheyear";
String search = "website";
String replace = "blog";
ByteBuffer input = ByteBuffer.wrap(fullText.getBytes());
byte[] toSearch = search.getBytes();
int index = getIndex(input, toSearch);

byte[] first = new byte[index];
input.get(first);

byte[] second = replace.getBytes();

input.position(input.position()+search.length());

ByteBuffer finalOne = ByteBuffer.allocate(first.length+second.length+input.remaining());
finalOne.put(first);
finalOne.put(second);
finalOne.put(input);
finalOne.flip();

CharBuffer result = Charset.forName("UTF-8").decode(finalOne);
String s = result.toString();
System.out.println(s);


}

public static int getIndex(ByteBuffer input , byte[] toSearch)
{
int index = -1 ;
while(input.hasRemaining() & index==-1)
{
boolean found = true ;
for(byte b : toSearch)
{
if(input.get()!=b)
{
found = false ;
break ;
}
}
if(found)
{
index= input.position()-toSearch.length;
}
}
input.rewind();
return index ;
}
}
Post Comments And Suggestions !!!Search And Replace String in ByteBuffer

Back to Featured Articles on Logo Paperblog