Reputation: 101
try {
File inFile = new File("books.txt");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile + "temp.txt");
BufferedReader br = new BufferedReader(new FileReader("books.txt"));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
String lineToRemove;
lineToRemove = JOptionPane.showInputDialog("Enter line to remove");
if (!line.trim().contains(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
I am trying to create a method that will delete a line of code in my .txt file if I enter a word that is contained in that line. My problem is that when I run this, the test says that it could not delete the file. Is there something wrong with the code? My code is also delimited with # if that may be adding to the problem. A sample output would be : Giants#James#1993
Upvotes: 0
Views: 919
Reputation: 2468
I've tested your code with minor changes (noted by @Andreas while I was writing this) and it works as expected
public static void main(String[] args) {
try {
File inFile = new File("C:\\rirubio\\books.txt");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File("C:\\rirubio\\books.txt" + "_temp");
BufferedReader br = new BufferedReader(new FileReader(inFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
String lineToRemove = JOptionPane.showInputDialog("Enter line to remove");
//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().contains(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Upvotes: 1