5、读取文件流进行全局替换,适合小文件
public static void main(String[] args){
String filePath = "D:\\sql\\UT_PERSON_INFO.sql";
String outPath = "D:\\sql\\UT_PERSON_INFO.sql";
try {
autoReplace(filePath,outPath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void autoReplace(String filePath, String outPath) throws IOException {
File file = new File(filePath);
Long fileLength = file.length();
byte[] fileContext = new byte[fileLength.intValue()];
FileInputStream in = new FileInputStream(filePath);
in.read(fileContext);
in.close();
String str = new String(fileContext);
str = str.replace("\"PUBLIC\".", " ");
str = str.replace("\"", "'");
PrintWriter out = new PrintWriter(outPath);
out.write(str.toCharArray());
out.flush();
out.close();
}
读取文件,每行读取,然后替换指定的内容:
public static void ChangeFile (String filePath, String outPath) throws IOException {
try {
BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath))));//数据流读取文件
StringBuffer strBuffer = new StringBuffer();
String empty = "";
String tihuan = "";
for (String temp = null; (temp = bufReader.readLine()) != null; temp = null) {
// if(temp.indexOf("/*") != -1 && temp.indexOf("*/") != -1){ //判断当前行是否存在想要替换掉的字符 -1表示存在
// tihuan = temp.substring(0, 10);
// temp = temp.replace(tihuan, empty);//替换为你想要的东东
// }
if(temp.contains("\"PUBLIC\".")) {
temp = temp.replace("\"PUBLIC\"."," ");
}
if(temp.contains("\"")) {
temp = temp.replace("\"","'");
}
strBuffer.append(temp);
strBuffer.append(System.getProperty("line.separator"));//行与行之间的分割
}
bufReader.close();
PrintWriter printWriter = new PrintWriter(outPath);//替换后输出的文件位置
printWriter.write(strBuffer.toString().toCharArray());
printWriter.flush();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}