0
我想創建一個jar文件,它分析目錄中的所有文件尋找提供的字符串,並用提供的字符串+ .getInstance()替換它,我有這樣的代碼:Java FileIO錯誤沒有分析所有類
public static String toAnalyze;
public static String path;
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java InstanceFixer <To Analyze> <Path>");
System.exit(1);
}
toAnalyze = args[0];
path = args[1];
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date resultDate = new Date(System.currentTimeMillis());
LoggingUtils.log("Instance Fixer","Started InstanceFixer on analysis " + toAnalyze + " at " + sdf.format(resultDate));
startIterating();
}
public static void startIterating() {
File dir = new File(path);
System.out.println(dir);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
filterFile(child);
}
LoggingUtils.log("Iterator","Analyzed " + directoryListing.length + " files.");
} else {
LoggingUtils.log("Iterator", path + " is not valid \n won't be able to Analyze files (if any).");
}
}
public static void filterFile(File file) {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
String read = in.readLine();
if (read.contains(toAnalyze + "Manager")) {
out.write(read.replace(toAnalyze + "Manager", toAnalyze + "Manager.getInstance()"));
LoggingUtils.log("Filter","Analyzed file " + file.getName() + ", found and fixed instance.");
out.close();
} else {
LoggingUtils.log("Filter","Analyzed file " + file.getName() + ", didn't find anything to rename, skipped.");
}
in.close();
} catch (IOException e) {
LoggingUtils.log("Filter","There was a problem: " + e);
e.printStackTrace();
}
}
問題是,它只是在第一行或最後一行進行搜索,而不是將其寫入舊文本的文本。我能做些什麼來解決這個問題?
請問您能提供一些代碼嗎? – ItsErikR
@ user3241491新增示例。這是不完全一樣的事情,你想完成,但應該給你基本的想法。 – Pshemo
@ user3241491實際上最後部分(與包含數據的新版本的臨時替換一個原始文件)可以使用'Files.copy被縮短(tmp.toPath(),original.toPath(),StandardCopyOption.REPLACE_EXISTING);' – Pshemo