输入文件的位置,输出文件的位置:
package utils;
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.regex.Matcher; import java.util.regex.Pattern;
/** * 把大写字符转换成下划线加上小写字母 * @author szd * */ public class ChangeUpper { public static void main(String[] args) { File fileInput = new File(args[0]); File fileOutput = new File(args[1]); BufferedReader bufferedReader = null; BufferedWriter bufferedWriter = null; try { bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileInput))); bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOutput))); String readLine = null; while((readLine=bufferedReader.readLine())!=null){ String replace = replace(readLine); bufferedWriter.write(replace); bufferedWriter.newLine(); } bufferedWriter.close(); bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } } public static String replace(String line){ String pattern = "\\B[A-Z]"; Pattern p = Pattern.compile(pattern); Matcher matcher = p.matcher(line); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, "_"+matcher.group().toLowerCase()); } matcher.appendTail(sb); return sb.toString(); // 结果:Abcdfsda_dfde /* Pattern p = Pattern.compile("cat"); Matcher m = p.matcher("one cat two cats in the yard"); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, "dog"); } // m.appendTail(sb); // 不加这句的话 结果是one dog two dog 加上这句话结是one dog two dogs in the yard System.out.println(sb.toString());*/ }
}