简体   繁体   中英

File won't delete

for some reason my file won't delete using f.delete(); and temp.txt will not be renamed to 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. 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 ; (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.
  • 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.
  • A Stream version is used for reading, which has one drawback: the passed lambda may not throw an IOException. Also the "loop counter" lineno must not be assigned to, so cannot be an int. Maybe use Files.newBufferedReader .

Simpler:

The class Files one should know, as it provides many utility calls.

/** @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; You create FileWriter, which will create temp.txt and output to it. However, your variable file1 was initialized before filewriter created it. (Btw, you can check if file exists with 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. This way you are sure it was created and will be able to rename it successfully

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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