我似乎想不通。在下面的方法中,我尝试将布尔值写入 2 个位置的文件,但实际上什么都没有写入。任何帮助将不胜感激。
private void renameTables(){
String path = MessengerMain.getInstance().getDataFolder() + File.separator + "v3-0-0 Table Rename.txt";
File f = new File(path);
try(ResultSet rs = conn.getMetaData().getTables(null, null, "%", null); Writer w = new PrintWriter(new FileOutputStream(f, false))){
if (!f.exists()){
f.createNewFile();
w.write("false");
w.flush();
}
List<String> lines = Files.readAllLines(Paths.get(path));
if (lines.get(0).equalsIgnoreCase("false")){
System.out.println("[Messenger] Verifying table names...");
int count = 0;
List<String> tables = new ArrayList<String>();
tables.add("messages");
tables.add("scores");
tables.add("contacts");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
if (tables.contains(table)){
update("ALTER TABLE " + table + " RENAME TO " + ("messenger_" + table) + ";");
count++;
}
}
if (count > 0){
System.out.println("[Messenger] Done. " + count + " table" + (count == 1 ? "" : "s") + " renamed.");
}else{
System.out.println("[Messenger] Done. No tables need to be renamed.");
}
w.write("true");
w.flush();
}
} catch (SQLException | IOException e){
e.printStackTrace();
}
}
遵循Elliot Frisch的建议(相同的结果):
private void renameTables(){
String path = MessengerMain.getInstance().getDataFolder() + File.separator + "v3-0-0 Table Rename.txt";
File f = new File(path);
try(ResultSet rs = conn.getMetaData().getTables(null, null, "%", null)){
Writer w = new PrintWriter(new FileOutputStream(f, false));
if (!f.exists()){
f.createNewFile();
w.write("false");
w.close(); //close here
}
List<String> lines = Files.readAllLines(Paths.get(path));
if (lines.get(0).equalsIgnoreCase("false")){
System.out.println("[Messenger] Verifying table names...");
int count = 0;
List<String> tables = new ArrayList<String>();
tables.add("messages");
tables.add("scores");
tables.add("contacts");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
if (tables.contains(table)){
update("ALTER TABLE " + table + " RENAME TO " + ("messenger_" + table) + ";");
count++;
}
}
if (count > 0){
System.out.println("[Messenger] Done. " + count + " table" + (count == 1 ? "" : "s") + " renamed.");
}else{
System.out.println("[Messenger] Done. No tables need to be renamed.");
}
w = new PrintWriter(new FileOutputStream(f, false)); //create a new writer
w.write("true");
w.close(); //close here
}
} catch (SQLException | IOException e){
e.printStackTrace();
}
}
这是一个完整的最小、完整、可验证的示例
public static void main(String[] args) {
File f = new File(System.getProperty("user.home"), "temp.txt");
String path = f.getPath();
try (Writer w = new FileWriter(f)) {
w.write("false");
} catch (IOException e) {
e.printStackTrace();
}
try {
List<String> lines = Files.readAllLines(Paths.get(path));
System.out.println(lines);
} catch (IOException e) {
e.printStackTrace();
}
}
输出是(如预期)
[false]