を使用してテキストファイルから行ずつ削除それらの2行を1つずつ読み込んで削除したい。正常に私はそれらの2行を読むが、それらを削除すると、それは失敗します。これは私のコードです。どのように読んで、私は2行が</p> <ul> <li>のHello Worldを好き1.</li> <li>のHello World 2</li> </ul> <p>Iを含むテキストファイルを持っているのjava
@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
です。前もって感謝します。