【发布时间】:2021-06-10 16:33:39
【问题描述】:
我想删除“db.txt”(programPath[1])。我检查了代码并关闭了所有 Scanners 和 BufferedReaders。当我尝试删除时,它返回 false。我尝试使用 VisualVM 调试我的代码,但我找不到任何错误。我以两种方法使用了该文件。为了获得更好的可见性,我在打开和关闭文件 (TODO) 时标记了该位置。这是 第一种方法:
public static void changePassword(boolean isLogged, String[] programPath, File db) {
if (!isLogged) {
login(isLogged, programPath, db);
}
File tempFile = new File(programPath[2]);
File tempDbFile = new File(programPath[0] + File.separator + "tempDb.txt");
try {
BufferedReader tempFileScanner = new BufferedReader(new FileReader(tempFile));
BufferedReader dbScanner = new BufferedReader((new FileReader(db))); // TODO db open
//Scanner dbScanner = new Scanner(db);
FileWriter tempDbWriter = new FileWriter(tempDbFile);
if (!tempDbFile.exists()){
try {
tempDbFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("created");
}
String[] lineToRemove = tempFileScanner.readLine().split("\\:");
tempFileScanner.close();
String line;
while((line = dbScanner.readLine()) != null) {
System.out.println("Line: " + line);
System.out.println("Line to remove: " + lineToRemove[0] + ":" + lineToRemove[1]);
if(line.equals(lineToRemove[0] + ":" + lineToRemove[1])){
tempDbWriter.write(lineToRemove[0] + ":" + newPass + System.getProperty("line.separator"));
continue;
}
tempDbWriter.write(line + System.getProperty("line.separator"));
System.out.println("Written: " + line);
}
tempDbWriter.close();
dbScanner.close(); // TODO db closed
} catch (Exception e) {
e.printStackTrace();
}
if(db.delete()){
System.out.println("File deleted");
} else if(!db.delete()){
System.out.println("File not deleted. W H Y ?");
}
}
第二种方法:
public static boolean checkCredentials(String[] programPath, File db){
Scanner scan = new Scanner(System.in); // for getting user input
System.out.println("Please insert your card number: ");
String cardNr = scan.nextLine();
System.out.println("Please insert your PIN: ");
String pin = scan.nextLine();
try {
Scanner dbScanner = new Scanner(db); // TODO db open
//now read the file line by line...
while (dbScanner.hasNextLine()) {
String[] line = dbScanner.nextLine().split("\\:");
System.out.println("CardNr: " + cardNr);
System.out.println("Pin: " + pin);
if(line[0].equals(cardNr) && line[1].equals(pin)) {
String[] loggedInAs = {line[0], line[1]};
tempFile.createTempFile(programPath, loggedInAs);
return true;
}
}
dbScanner.close(); // TODO db close
} catch(FileNotFoundException e) {
//handle this
}
return false;
}
谁能解释我做错了什么?或者如何查看打开的位置?
附:我有权删除/修改文件
【问题讨论】:
-
首先,检查您是否有删除文件的权限。
-
我有。另一个班级正在删除一个文件,我没有问题。我编辑了问题。
-
你在哪一行写了 file.delete() 抱歉,我好像没找到。
-
第一种方法,在最后几行。有一个if语句;该语句检查文件是否被删除。
-
你能举个小例子吗?
标签: java java.util.scanner bufferedreader