title: Cannot delete file Java
body: <p>I have this method that gets the last line of a .txt file and creates a new temp file without that line. But when I try to delete the .txt that has the line I want to delete (so then I can rename the temp file) for some reason I can't. This is the code:</p>
  
  <pre><code>void removeFromLocal() throws IOException {
      String lineToRemove = getLastLine();
      File inputFile = new File("nexLog.txt");
      File tempFile = new File("TempnexLog.txt");
      BufferedReader reader = null;
      BufferedWriter writer = null;
      try {
  
          reader = new BufferedReader(new FileReader(inputFile));
          writer = new BufferedWriter(new FileWriter(tempFile));
  
          String currentLine;
          int i = 0;
          while ((currentLine = reader.readLine()) != null) {
              i++;                
              String trimmedLine = currentLine.trim();
              if (!trimmedLine.equals(lineToRemove)) {
                  if (i != 1) {
                      writer.newLine();
                  }
                  writer.write(currentLine);
              }
          }
              reader.close();
              reader = null;
              writer.flush();
              writer.close();
              writer = null;
              System.gc();
  
              inputFile.setWritable(true);
  
              if (!inputFile.delete()) {
                  System.out.println("Could not delete file");
                  return;
              }
  
  
              if (!tempFile.renameTo(inputFile)) {
                  System.out.println("Could not rename file");
              }
          //boolean successful = tempFile.renameTo(inputFile);
      } catch (IOException ex) {
          Logger.getLogger(dropLog.class.getName()).log(Level.SEVERE, null, ex);
      }
  }
  </code></pre>
  
  <p>Whats funny is that when I press the button that calls the method once, nothing happens ("Could not delete file"), the second time it works fine and the 3rd I get "Could not rename file".</p>