package se.kth.isk.leffe.fileutil; import java.io.IOException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; /** * This class handles replecement of one String with another in a file. */ public class Replace { private File file; private Charset charSet; /** * Constructs a Replace that handles replacements in the * specified file that is encoded with the specified charset. */ public Replace(String fileName, String cs) { this.file = new File(fileName); charSet = Charset.forName(cs); } /** * Replaces all occurences of from with to. This simple version assumes that * from and to are of the same length. * * @param from The String that is replaced. * @param to The replacing String. * @return The number of replacements that occured. * @exception IOException if thrown by the underlying file io methods. * @exception IllegalArgumentException if from.length() != to.length. */ public int replace(String from, String to) throws IOException { if (from.length() != to.length()) { throw new IllegalArgumentException(); } CharBuffer content = openCharBuffer(); int numOfHits = replace(content, from, to); saveCharBuffer(content); return numOfHits; } private CharBuffer openCharBuffer() throws IOException { FileChannel fc = new FileInputStream(file).getChannel(); MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); return charSet.decode(mbb); } private void saveCharBuffer(CharBuffer cb) throws IOException { ByteBuffer bb = charSet.encode(cb); FileChannel fc = new FileOutputStream(file).getChannel(); fc.write(bb); } private int replace(CharBuffer content, String f, String to) { int numOfHits = 0; char[] from = f.toCharArray(); for (int contPos=0; contPos