以下代码旨在用用户提供的字符串替换现有字符串。虽然在MyEclipse中工作正常但通过命令提示符无法正常工作。
以下方法将读取目录/子目录中的所有文件 并用目标字符串替换源字符串并重写整个文件。
public static void CopyandWriteall(String directoryName, String source,
String destination) {
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
int changed_count = 0;
int total_count = 0;
int filechange_count = 0;
for (File file : fList) {
filechange_count = 0;
newXml = "";
if (file.isFile()) {
String filePath = file.getAbsolutePath();
// System.out.println(filePath);
String fileName = filePath
.substring(filePath.lastIndexOf("\\"));
String fileExtension = fileName.substring(fileName
.lastIndexOf(".") + 1);
BufferedReader br = null;
String CurrentLine;
try {
br = new BufferedReader(new FileReader(file));
while ((CurrentLine = br.readLine()) != null) {
if (CurrentLine.contains(source)) {
filechange_count++;
CurrentLine = CurrentLine.replaceAll(source,
destination);
// changed_count++;
// filechange_count++;
}
newXml = CurrentLine + "\n";
}
System.out.println("filePath====" + filePath + fileName
+ "=======filechange_count===" + filechange_count);
File NewXmlfile = new File(filePath);
// System.out.println(directoryName+"\\updatedFiles"
// +fileName);
FileWriter fw = new FileWriter(NewXmlfile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(newXml);
bw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else if (file.isDirectory()) {
CopyandWriteall(file.getAbsolutePath(), source, destination,
LogPath);
System.out.println(file.getAbsolutePath());
}
// System.out.println(newXml);
total_count++;
}
}
}