gpt4 book ai didi

java - 为什么当我想从文本文件中删除字符串时它不起作用?

转载 作者:行者123 更新时间:2023-12-02 02:27:53 28 4
gpt4 key购买 nike

我尝试从java中的文本文件中删除字符串,但数据仍然保持不变。

尝试{

        //removing row from table
mod = (DefaultTableModel) table.getModel();
int SelectedRowIndex = table.getSelectedRow();
String day = table.getValueAt(SelectedRowIndex, 0).toString();
String date = table.getValueAt(SelectedRowIndex, 1).toString();
String venue = table.getValueAt(SelectedRowIndex, 2).toString();
String from = table.getValueAt(SelectedRowIndex, 3).toString();
String to = table.getValueAt(SelectedRowIndex, 4).toString();
String temp = day + "|" + date + "|" + venue + "|" + from + "|" + to;
System.out.println(temp);
mod.removeRow(SelectedRowIndex);

//scanning data from file and removing data from file based on
//selected option in table
File inputFile = new File("Consultation Hours.txt ");
File tempFile = new File("Updated Consultation Hours.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;

while ((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if (trimmedLine.equals(SelectedRowIndex)) {
continue;
}
writer.write(currentLine + System.lineSeparator());

}

writer.close();
reader.close();

boolean successful = tempFile.renameTo(inputFile);

我一直在寻找不同的方法,但仍然失败,有人知道我哪里出错了吗?

最佳答案

正如其他人所解释的,您正在将选定的行索引与实际文本行进行比较 - 这使得 if 条件始终为 false。您可以为每一行创建一个索引并跳过与所选行索引匹配的行,如下所示。

int index = 0;
while ((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if (index++ == SelectedRowIndex)) {
continue;
}
writer.write(currentLine + System.lineSeparator());
}

关于java - 为什么当我想从文本文件中删除字符串时它不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57244600/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com