【问题标题】:Iterative function issue迭代函数问题
【发布时间】:2014-03-08 13:09:42
【问题描述】:

我编写的函数存在一些问题。该函数基本上将一个文件和一个字符串作为参数放入方法中,并在文件中搜索该字符串并将其替换为“”。

public void removeReminder(File a, String search) throws IOException {

    File tempFile = File.createTempFile("file", ".txt", a.getParentFile());
    BufferedReader br = new BufferedReader(new FileReader(a));
    PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

    for (String line; (line = br.readLine()) != null;) {
        line = line.replace(search, "");
        pw.println(line);
    }
    br.close();
    pw.close();

    a.delete();

    tempFile.renameTo(a);
}

然后我有 3 个文本文件需要运行此方法。下面是我运行该函数的代码。

removeButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    // TODO
                    try {


                    String names = reminderNameField.getText();
                    String date = reminderDate.getText();
                    String details = reminderDetailsField.getText();

                    File fileName = new File("reminderNames.txt");
                    File fileDate = new File("reminderDate.txt");
                    File fileDetails = new File("reminderDetails.txt");


                        removeReminder(fileName, names);
                        removeReminder(fileDate, date);
                        removeReminder(fileDetails, details);
                    } catch (IOException e){
                        e.printStackTrace();
                    }

我不知道为什么这不起作用。它适用于第一次迭代(例如 removeReminder(fileName, names);)但它不适用于其他迭代,它似乎只是忽略它们:s 谁能告诉我这是为什么?

【问题讨论】:

  • 你能更具体地说明“不起作用”吗?文件是空的吗?
  • 它用“removeReminder(fileName, names);”清空第一个文件但它对其他文件没有任何作用。它从 fileName 中删除字符串,但将字符串保留在 fileDate + fileDetails 中。 :s
  • 检查 delete() 返回的内容。如果为 false,则表示删除不成功,导致重命名失败,您将查看原始文件。尝试将结果写入新文件,并传入带有 .res 后缀的文件名。并且不要删除和重命名。检查结果。
  • 是的,它似乎在删除方面失败了。它无法删除文件,因此它只是向我显示原始文件,我该如何解决这个问题?
  • 也许您有另一个进程正在访问该文件?如果在 Windows 上,您可以使用 sysinternal 套件中的进程资源管理器实用程序并查找正在访问文件的进程。另一种方法是按照 b4 的建议写入不同的文件,例如 File temp=new File(a.getParentFile(),a.getName()+".res")

标签: java string function jbutton file-handling


【解决方案1】:

我总是冲洗打印机。在调用 close() 之前尝试刷新 PrintWriter。

pw.flush();

【讨论】:

  • 试过这个但没有运气:S,我只是不明白为什么它适用于该方法的第一次调用,但不适用于接下来的两个?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2018-09-02
  • 2019-02-27
  • 2015-04-29
  • 1970-01-01
相关资源
最近更新 更多