简体   繁体   English

文件不会删除

[英]File won't delete

for some reason my file won't delete using f.delete();出于某种原因,我的文件不会使用 f.delete() 删除; and temp.txt will not be renamed to Materials.txt.并且 temp.txt 不会重命名为 Materials.txt。 I couldn't figure out what was wrong, it outputted false, I ran NetBeans as administrator in order to make sure it had permissions to delete the file, and the code before which is taking the editing a line works fine, other than the fact it is on temp which is not being changed to Materials.txt.我不知道出了什么问题,它输出错误,我以管理员身份运行 NetBeans 以确保它有权删除文件,并且在编辑一行之前的代码工作正常,除了事实它处于临时状态,不会更改为 Materials.txt。 Any help is appreciated, thanks!任何帮助表示赞赏,谢谢!

try {
    DefaultTableModel model= (DefaultTableModel)Table.getModel();
    int selectedRowIndex = Table.getSelectedRow();

    File f= new File("Materials.txt");
    File file1= new File("temp.txt");
    FileReader fr= new FileReader("Materials.txt");
    BufferedReader br= new BufferedReader(fr);
    FileWriter fw= new FileWriter("temp.txt", true);

    String updated = (jTextField1.getText()+","+jTextField2.getText()+","+jTextField3.getText()+","+jTextField4.getText()+","+jTextField5.getText()+","+jTextField6.getText()+"\r\n");
    String temp;
    int a=0;

    while (a<=selectedRowIndex)
    {
        a++;
        String line= br.readLine();
        fw.write(line+"\r\n");
    }
    br.readLine();
    fw.write(updated);

    while (br.ready()==true)
    {
        temp=br.readLine();
        fw.write(temp+"\r\n");
    }

    fw.close();
    br.close();
    fr.close();

    System.out.println(f.delete());
    file1.renameTo(f);
}
catch (IOException e){
    System.err.println(e);
}

Edit: Updated code trying to implement a suggest solution, the line with "void updateMaterialsFile(int updatedLineno = 0, String updated) throws IOException {" is throwing errors stating illegal start of expression, expecting ;编辑:尝试实施建议解决方案的更新代码,带有“void updateMaterialsFile(int updatedLineno = 0, String updated) throws IOException {”的行抛出错误,说明表达式的开始非法,期望; (multiple times) and not a statement. (多次)而不是声明。 Ty as always.泰一如既往。

try {
   DefaultTableModel model= (DefaultTableModel)Table.getModel();
   int selectedRowIndex = Table.getSelectedRow();


   String updated = (jTextField1.getText()+","+jTextField2.getText()+","+jTextField3.getText()+","+jTextField4.getText()+","+jTextField5.getText()+","+jTextField6.getText()+"\r\n");

  void updateMaterialsFile(int updatedLineno = 0, String updated) throws IOException {
   Path materialsPath = Paths.get("Materials.txt");
   Path tempPath = materialsPath.resolveSibling("temp.txt");

   try (BufferedReader fr = Files.newBufferedReader(materialsPath);
           BufferedWriter fw = Files.newBufferedWriter(tempPath);) {

       for (int lineno = 0; ; ++lineno) {
           String line = fr.readLine();
           if (line == null) {
               break;
           }
           fw.write(lineno == updatedLineno ? updated : line);
           fw.write("\r\n");
       }
   } // Automatically closes fr and fw
   Files.move(tempPath, materialsPath, StandardCopyOption.REPLACE_EXISTING);
}
}
catch (IOException e){
   System.err.println(e);
}

Not entirely clear about a timing problem for the deletion, as everything seems to be closed at least once.不完全清楚删除的时间问题,因为一切似乎都至少关闭了一次。

void updateMaterialsFile(int updatedLineno, String updated) throws IOException {
    Path materialsPath = Paths.get("Materials.txt");
    Path tempPath = materialsPath.resolveSibling("temp.txt");

    try (Stream<String> lines = Files.lines(materialsPath);
            BufferedWriter fw = Files.newBufferedWriter(tempPath)) {

        AtomicInteger lineno = new AtomicInteger();
        lines.forEach(line -> {
            int lno = lineno.getAndIncrement();
            try {
                fw.write(lno == updatedLineno ? updated : line);
                fw.write("\r\n");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    } catch (RuntimeException e) {
        throw new IOException(e.getCause());
    }
    Files.move(tempPath, materialsPath, StandardCopyOption.REPLACE_EXISTING);
}
  • The code above uses a newer style, the temp file uses the same file system in Path.上面的代码使用了较新的样式,临时文件在 Path 中使用相同的文件系统。
  • The rename (move) does the deleting in one step.重命名(移动)一步完成删除。
  • You could also use a temporary file (see Files), which might be on a faster file system.您还可以使用临时文件(请参阅文件),它可能位于更快的文件系统上。
  • Using try-with resources automatically closes, even when returning, breaking, throwing an exception.使用 try-with 资源会自动关闭,即使在返回、中断、抛出异常时也是如此。
  • A Stream version is used for reading, which has one drawback: the passed lambda may not throw an IOException. Stream 版本用于读取,它有一个缺点:传递的 lambda 可能不会抛出 IOException。 Also the "loop counter" lineno must not be assigned to, so cannot be an int.此外,不得将“循环计数器” lineno分配给,因此不能是 int。 Maybe use Files.newBufferedReader .也许使用Files.newBufferedReader

Simpler:更简单:

The class Files one should know, as it provides many utility calls.Files应该知道,因为它提供了许多实用程序调用。

/** @param updateLineno counted from 0. */
void updateMaterialsFile(int updatedLineno, String updated) throws IOException {
    Path materialsPath = Paths.get("Materials.txt");
    Path tempPath = materialsPath.resolveSibling("temp.txt");

    try (BufferedReader fr = Files.newBufferedReader(materialsPath);
            BufferedWriter fw = Files.newBufferedWriter(tempPath)) {

        for (int lineno = 0; ; ++lineno) {
            String line = fr.readLine();
            if (line == null) {
                break;
            }
            fw.write(lineno == updatedLineno ? updated : line);
            fw.write("\r\n");
        }
    } // Automatically closes fr and fw
    Files.move(tempPath, materialsPath, StandardCopyOption.REPLACE_EXISTING);
}

- ——

What I assume is going on: you do not have file temp.txt;我假设正在发生的事情:您没有文件 temp.txt; You create FileWriter, which will create temp.txt and output to it.您创建 FileWriter,它将创建 temp.txt 并输出到它。 However, your variable file1 was initialized before filewriter created it.但是,您的变量 file1 在 filewriter 创建之前已初始化。 (Btw, you can check if file exists with File#exists). (顺便说一句,您可以使用 File#exists 检查文件是否存在)。 So you can do many things to change it, but the easiest would be to move initialization of new File("temp.txt") to the end of the method.所以你可以做很多事情来改变它,但最简单的方法是将 new File("temp.txt") 的初始化移动到方法的末尾。 This way you are sure it was created and will be able to rename it successfully这样您就可以确定它已创建并且能够成功重命名它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM