0
我正在創建一個JFrame,用戶將能夠在該文件中插入新的方法。如果該文件不存在,程序將創建新文件,然後在其中插入該方法。如果該文件已經存在,它將嘗試創建具有給定名稱的新方法,但如果該文件包含具有相同名稱的方法,則會爲用戶提供警報。如何獲取更新的文件文本
我能夠正確地做所有這些事情,唯一的問題是在類文件中創建新方法後,如果用戶再次單擊Create Method按鈕,應用程序不會拋出任何警報,因爲它無法讀取文件中的新方法名稱。當我檢查文件內容時,我可以看到新的方法,但不知何故,我的代碼無法從文件中讀取新代碼。這是相同的代碼。
File f = null;
f = new File(Report.path + "//src//_TestCases//" + tc_name + ".java");
if (!f.exists()) {
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
f.createNewFile();
bw.write(testcase);
bw.close();
}
Class<?> c = Class.forName("_TestCases." + tc_name);
Method[] m = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
if (m[i].getName().toLowerCase()
.equals(module_name.toLowerCase())) {
JOptionPane
.showMessageDialog(null,
"Module with the given name already exists. Please provide other name.");
return false;
}
}
List<String> lines = Files.readAllLines(f.toPath(),
StandardCharsets.UTF_8);
String text = "";
if (lines.contains(" @AfterClass")) {
text = " @AfterClass";
} else {
text = "@AfterClass";
}
lines.add(lines.indexOf(text), "@Test\npublic void " + module_name
+ "() throws Exception {\n");
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
for (int i = 0; i < tc_values.size(); i++) {
lines.add(lines.indexOf(text), tc_values.get(i));
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
}
lines.add(lines.indexOf(text), "\n}\n");
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
您是否重新打開了create方法代碼中的文件? – zombie
不管代碼是什麼,我已經在上面提及過了,創建一個新方法不是問題。我能夠創建新的方法,問題是從文件中讀取這些新創建的方法。 – Naseem
您是否嘗試過重新打開文件。我的意思是在你創建新方法後,關閉文件然後再打開它。我想出了http://stackoverflow.com/questions/16383578/how-to-update-the-contain-in-txt-file-java使用Google搜索 – pahan