1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| package com.xxxx;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestSearchReplace {
/**
* Remplacement de la chaine 'are' par 'is'
* du fichier "test.text" qui contient la chaine "Java are fun"
* @param args
*/
public static void main(String[] args) {
try {
// Chargement du fichier "test.txt" qui contient la chaine
// "Java are fun"
Pattern pat = Pattern.compile("are");
Matcher mat = pat.matcher(fromFile("test.txt"));
// Remplace 'are' par 'is'
String sentence = mat.replaceAll("is"); // 'Java is fun.'
System.out.println(sentence);
}
catch (Exception e) {
System.out.println(e);
}
}
/**
* Retourne CharSequence du contenu du fichier filename
* @param filename
* @return
* @throws IOException
*/
public static CharSequence fromFile(String filename) throws IOException {
FileInputStream fis = new FileInputStream(filename);
FileChannel fc = fis.getChannel();
// Create a read-only CharBuffer on the file
ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int)fc.size());
CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
return cbuf;
}
} |
Partager