在为我的班级创建方法时,我遇到了意想不到的问题。我尝试过其他方面的解决方案,但他们只是不为我工作。我的方法应该只是找到指定的行,复制文件跳过不必要的行,删除原始文件并将临时文件重命名为原始文件的名称。它成功地按预期创建了新文件,但由于无法将临时文件重命名为原始文件,因此无法删除之前的文件。我无法弄清楚,为什么?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
答案 0 :(得分:1)
试试这段代码:
// This will store the number of correct guesses that have been made
var correctAnswers = 0;
答案 1 :(得分:1)