是的,我已经搜索了通过比较和匹配删除特定行的方法,但是我的情况与我搜索的情况不同,并且发生了错误的操作。
这里的代码是actionPerformed
按钮btnRemove
。它的作用是从表格中删除选定的单元格,并且还意味着从文件中删除相应的单元格(字符串)值Activities.dat
但是,发生的情况是代码使整个文件被删除并变为空白,留下 1 个空行,而不仅仅是我想要删除的行。
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
if (row >= 0) {
if (column >=0) {
for(int i=0; i<5; i++)
{
table.setValueAt("", row, column);
}
}
}
File file1 = new File("Activities.dat");
try
{
BufferedWriter writer = new BufferedWriter(new FileWriter(file1));
BufferedReader reader = new BufferedReader(new FileReader(file1));
Object lineToRemove = table.getValueAt(row, column);
lineToRemove.toString();
System.out.print(lineToRemove);
String currentLine;
while((currentLine = reader.readLine()) != null)
{
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
Object lineToRemove = table.getValueAt(row, column);
lineToRemove.toString();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine);
}
writer.close();
}
catch (IOException ex)
{
Logger.getLogger(ActivityScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
});