다음 코드를 사용자 지정 메서드에 추가했습니다.줄을 제거한 후 temp.txt의 이름을 original.txt로 바꿀 수 없습니다.
File inputFile = new File("F:\\EmployeePunch\\EmployeePunch\\src\\employeepunch\\original.txt"); // Your file
File tempFile = new File("F:\\EmployeePunch\\EmployeePunch\\src\\employeepunch\\temp.txt");// temp file
BufferedReader reader = null;
BufferedWriter writer = null;
try{
reader = new BufferedReader(new FileReader(inputFile));
writer = new BufferedWriter(new FileWriter(tempFile));
String firstName = chosenEmployee.getFirstName();
String lastName = chosenEmployee.getLastName();
String currentLine;
while((currentLine = reader.readLine()) != null) {
if(currentLine.contains(firstName)
&& currentLine.contains(lastName)) continue;
writer.write(currentLine);
}
}
catch (IOException e) {
e.printStackTrace();
}finally{
try {
inputFile.delete();
writer.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
} catch (IOException ex) {
ex.printStackTrace();
}
}
문제는 다음과 같습니다. 프로그램을 실행할 때마다 renameTo
이 실패합니다. 하지만 제거 된 것으로 가정 된 줄로 temp.txt가 올바르게 제거됩니다.
왜 renameTo
은 항상 false를 반환하나요?
편집 1 : 파일은 Windows의 다른 곳에서는 열 수 없습니다. 그들은 내 IDE의 프로젝트 탐색기에 나열되어 있지만 내 IDE에 의해 열리지 않습니다.
는
같습니다 BufferedReader'. 따라서 파일은 아직 열려 있습니다. – anonymous