를 사용하여 텍스트 파일에서 선으로 줄을 삭제 그 2 행을 하나씩 읽고 싶습니다. 성공적으로 나는 그 두 줄을 읽었지 만 나는 그것들을 삭제할 때 실패한다. 이것은 내 코드입니다.어떻게 읽고 나는 2 선</p> <ul> <li>안녕하세요을 좋아하는 1</li> <li>안녕하세요 2.</li> </ul> <p>I이 포함 된 텍스트 파일을 자바
@FXML
public void buttonLineDeleteAction(ActionEvent event) throws IOException {
try {
String line = null;
final File fileGpNumber = new File(filePath);
FileReader fileReader = new FileReader(fileGpNumber);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
System.out.println("Line--- " + line);
boolean result = removeLineFromFile(line);
System.out.println("Result---> " + result);
}
} catch (IOException e) {
System.out.println("IOException " + e);
}
}
그리고이 방법을 사용하여 줄을 제거하십시오.
private boolean removeLineFromFile(String lineToRemove) {
boolean isDeleted = false;
try {
File inFile = new File(filePath);
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(filePath));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
isDeleted = false;
} else {
isDeleted = true;
}
}
pw.close();
br.close();
//Delete the original file
if (inFile.delete()) {
isDeleted = true;
} else {
isDeleted = false;
System.out.println("Could not delete file.");
}
//Rename the new file to the filename the original file had.
if (tempFile.renameTo(inFile)) {
isDeleted = true;
} else {
System.out.println("Could not rename file.");
isDeleted = false;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return isDeleted;
}
이제 내 tempFile에서 해당 줄을 삭제하지만 inFile을 삭제하고 thetempFile 파일의 이름을 바꾸는 데 문제가 있습니다. 이 내 출력
Line--- Hello World 1.
Could not delete file.
Could not rename file.
Result---> false
Line--- Hello World 2.
Could not delete file.
Could not rename file.
Result---> false
인 나에게 사람을 도와주세요. 미리 감사드립니다.