Below code will find and replace the string
import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; public class FindReplace { private static byte[] sought; private static byte[] replacement; public static String varyingSessionId = null; private String SessionID = null; private static boolean matches(MappedByteBuffer bb, int pos) { for (int j = 0; j < sought.length; j++) { if (sought[j] != bb.get(pos + j)) { return false; } } return true; } private static void replace(MappedByteBuffer bb, int pos) { for (int j = 0; j < sought.length; j++) { byte b = j < replacement.length ? replacement[j] : 32; bb.put(pos + j, b); } } private static void searchAndReplace(MappedByteBuffer bb, int sz, String fileName) { int replacementsCount = 0; for (int pos = 0; pos <= sz - sought.length; pos++) { if (!matches(bb, pos)) continue; replace(bb, pos); pos += sought.length - 1; replacementsCount++; } } private static void patchSessionMethod(File f) throws IOException { RandomAccessFile raf = new RandomAccessFile(f, "rw"); FileChannel fc = raf.getChannel(); int sz = (int)fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_WRITE, 0L, sz); searchAndReplace(bb, sz, f.getName()); bb.force(); raf.close(); } public FindReplace(String replace) { this.SessionID = new ReadSession().getConfig("SessionId"); System.out.println("11.0.1 ***** Inside FindReplace Constructor ***** "); System.out.println("11.0.1.1 ***** New Search SessionID ***** " + this.SessionID); System.out.println("11.0.1.2 ***** Replace SessionID ***** " + replace); if (this.SessionID.length() != replace.length()) validateSessionSize(); else { varyingSessionId = replace; } sought = ("session=" + this.SessionID.trim()).getBytes(); replacement = ("session=" + replace.trim()).getBytes(); System.out.println("***** Reading Binary Files Path ***** " + ReadProperties.getConfig("BinaryFiles")); File f1 = new File(ReadProperties.getConfig("BinaryFiles")); File[] listOfFiles = f1.listFiles(); for (int i1 = 0; i1 < listOfFiles.length; i1++) { if (!listOfFiles[i1].isFile()) continue; String files = listOfFiles[i1].getName(); if ((!files.endsWith(".binary")) && (!files.endsWith(".BINARY"))) continue; File f = new File(files); try { patchSessionMethod(f); } catch (Exception x) { System.err.println(f + ": " + x); } } } public static void main(String[] args) { FindReplace FRC = new FindReplace("12345"); } }
Monday, 16 May 2011
Find and Replace exact string in java
Labels:
Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment