[英]Java remove lines from file
我試圖根據行中的2部分刪除文件中的行:書籍標題及其ID。 我希望用戶輸入兩者,如果它們都在一行中,請刪除該行。 這是我的代碼,但是唯一的問題是removeLine
說“無法從int轉換為string”。 有誰知道如何解決這一問題?
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");
}
JOptionPane.showConfirmDialog
返回一個int而不是一個String,因此您應該將removeLine的類型更改為int。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.