I am trying to delete a line in a file based on 2 parts in the line: the book title and its ID. I want the user to enter both and if they are both in a line, delete the line. This is the code I have however the only problem is that removeLine
says "cannot convert from int to string".
Does anyone know how to fix this?
File inFile = new File("books.txt");
if (!inFile.isFile()) {
return;
}
File tempFile = new File("books.txt" + "1");
BufferedReader br = new BufferedReader(new FileReader(inFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
JTextField xField = new JTextField(10);
JTextField yField = new JTextField(10);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Title:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("ID:"));
myPanel.add(yField);
String removeLine = JOptionPane.showConfirmDialog(null, myPanel,
"Remove", JOptionPane.OK_CANCEL_OPTION);
if (removeLine == JOptionPane.OK_OPTION) {
while ((line = br.readLine()) != null) {
if (!line.trim().contains(removeLine)) {
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");
}