行の2つの部分に基づいてファイル内の行を削除しようとしています:本のタイトルとそのID。ユーザーに両方を入力させ、両方が1行であれば、その行を削除します。これは私が持っているコードですが、唯一の問題はremoveLine
は "intから文字列に変換できません"ということです。 これを修正する方法を知っている人はいますか?Javaはファイルから行を削除します
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");
}
*私はtryLineをintに変更しようとしていたのですが、removeLineをインクルードすると "メソッドには文字列のCharSequenceが含まれています"というエラーが返されます。 – jkjk
あなたのソリューションはここで説明されていると思うhttp://stackoverflow.com/questions/6555040/multiple-input-in-joptionpane-showinputdialog xFieldとyFieldからユーザが導入した値は回復しません。 removeLineにはJOptionPane.OK_OPTIONまたはJOptionPane.CANCEL_OPTIONのみが含まれ、削除する本は含まれません – RubioRic