java无法删除/重命名文件
我想用tempFile的内容更新我的inputFile。。但它不允许我删除或重命名。。我需要帮助
try{
reader = new BufferedReader(new FileReader(inputFile));
out = new PrintWriter(new BufferedWriter(new FileWriter(tempFile, true)));
Scanner scan = new Scanner(System.in);
String word = "";
while(!word.contentEquals("exit")){
System.out.println("Enter a command: ");
word = scan.nextLine();
String entries[] = word.split(" ");
if(word.startsWith("add")){
out.write(entries[1] + " " + entries[2]);
out.write("\r\n");
} else if (word.startsWith("remove")){
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.contains(entries[1])) continue;
//out.write(currentLine + System.getProperty("line.separator"));
}
} else if (word.equals("show")){
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
System.out.println(currentLine);
}
}
}
}
finally {
out.close();
out.flush();
reader.close();
}
//Delete the original file
if (!inputFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inputFile))
System.out.println("Could not rename file");
}
我的整个程序应该在文件中添加联系人或条目。然后用户可以删除或显示文本文件中的所有联系人。还有其他方法吗?我可以覆盖该文件而不是使用临时文件吗?如果是,我怎么做
它总是显示“无法重命名文件”或“无法删除文件”
# 1 楼答案
您不需要临时文件。根据经验,只有当我要关闭程序、重新打开程序并期望收到所述数据时,我才会写入文件。我将
out
设为StringBuilder
,并将每一行附加到它而不是文件。然后使用字符串生成器写回文件如果要保存文件以前的内容,请在写入任何内容之前将以前的内容写入
StringBuilder
如果希望保存以前的数据,请使用此选项