|
|
|
|
@ -6,22 +6,16 @@ import java.util.List;
|
|
|
|
|
|
|
|
|
|
public class ModifyClass {
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 查找目标名字所在行,并替换该行的第三个字符串
|
|
|
|
|
* @param filePath 文件路径
|
|
|
|
|
* @param targetName 要查找的名字(每行第一个字符串)
|
|
|
|
|
* @param newThirdString 新的第三个字符串
|
|
|
|
|
* @return 找到并替换的行号,未找到返回-1
|
|
|
|
|
*/
|
|
|
|
|
public static int modifyclass(String filePath, String targetName, String newThirdString) {
|
|
|
|
|
List<String> lines = new ArrayList<>();
|
|
|
|
|
int targetLineNumber = -1;
|
|
|
|
|
|
|
|
|
|
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
|
|
|
|
|
String line;
|
|
|
|
|
while ((line = reader.readLine()) != null) {
|
|
|
|
|
lines.add(line);
|
|
|
|
|
if (line.trim().isEmpty()) continue;
|
|
|
|
|
if (line.trim().isEmpty()) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
String[] parts = line.trim().split("\\s+");
|
|
|
|
|
if (parts.length > 0 && parts[0].equals(targetName)) {
|
|
|
|
|
targetLineNumber = lines.size();
|
|
|
|
|
@ -31,7 +25,6 @@ public class ModifyClass {
|
|
|
|
|
System.err.println("读取文件错误: " + e.getMessage());
|
|
|
|
|
return -1;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (targetLineNumber != -1) {
|
|
|
|
|
int index = targetLineNumber - 1;
|
|
|
|
|
String[] parts = lines.get(index).trim().split("\\s+");
|
|
|
|
|
@ -39,7 +32,9 @@ public class ModifyClass {
|
|
|
|
|
parts[2] = newThirdString;
|
|
|
|
|
lines.set(index, String.join(" ", parts));
|
|
|
|
|
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
|
|
|
|
|
for (String l : lines) writer.write(l + System.lineSeparator());
|
|
|
|
|
for (String l : lines){
|
|
|
|
|
writer.write(l + System.lineSeparator());
|
|
|
|
|
}
|
|
|
|
|
} catch (IOException e) {
|
|
|
|
|
System.err.println("写入文件错误: " + e.getMessage());
|
|
|
|
|
return -1;
|
|
|
|
|
@ -50,5 +45,4 @@ public class ModifyClass {
|
|
|
|
|
}
|
|
|
|
|
return targetLineNumber;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|