The code intended to replace an existing string with a string provided by user.its not working through CMD




The following code intended to replace an existing string with a user provided string.its not working properly through command prompt though its working fine in MyEclipse.



The following method will read all the files in a directory/sub directories and replace the source string with destination string and rewrite the whole file.



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++;
}

}


}


No comments:

Post a Comment