gpt4 book ai didi

java - 从 csv 读取,根据第一部分删除行

转载 作者:行者123 更新时间:2023-12-01 12:38:03 26 4
gpt4 key购买 nike

在我的应用程序中,我在 JList 中显示 CSV 每一行的第一部分,当选择它并按下按钮(删除)时,我希望它根据第一个条目从文件中删除该行。我正在尝试一种方法,您有一个临时文件,然后写入它,然后在最后重命名它,但由于某种原因,这不起作用。有什么想法吗?

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
// TODO add your handling code here:
// Delete service
String selected = (String) jList1.getSelectedValue();
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = new File("/users/aak7133/desktop/temp.txt");

try {
BufferedReader reader = new BufferedReader(new FileReader(passwords));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
//String trimmedLine = line.trim();

if (line.contains(selected)) {
continue;
}
writer.write(line);
}
boolean successful = temp.renameTo(passwords);

} catch (Exception e) {

}
updateList();
clearFields();

}

最佳答案

这个问题实际上是由开放的读者和作者造成的。这应该有效:

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
String selected = (String) jList1.getSelectedValue();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = File.createTempFile("temp", ".txt", new File("/users/aak7133/desktop/"));
reader = new BufferedReader(new FileReader(passwords));
writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
// String trimmedLine = line.trim();

if (line.contains(selected)) {
continue;
}
writer.write(line + "\n");
}
if (passwords.canWrite()) {
try {
reader.close();
reader = null;
} catch (IOException ignore) {}

try {
writer.close();
writer = null;
} catch (IOException ignore) {}

String path = passwords.getAbsolutePath();
passwords.delete();
boolean successful = temp.renameTo(new File(path));
System.out.println(successful);

}

} catch (Exception e) {

} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {}
}
if (writer != null) {
try {
writer.close();
} catch (IOException ignore) {}
}
}
updateList();
clearFields();
}

关于java - 从 csv 读取,根据第一部分删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25385952/

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