2014-07-15 11 views
10

Ho creato alcuni file per uso temporaneo e li ho usati come input per alcuni metodi. E ho chiamatodeleteOnExit non cancella file

deleteOnExit() 

su tutti i file che ho creato. Ma un file rimane ancora.

Suppongo che sia perché il file è ancora in uso, ma non il compilatore andare alla riga successiva solo dopo la riga corrente è fatto? (Filo singolo)

Mentre il suo non è un problema in pratica a causa di sovrascrittura java, c'è sempre un solo file. Vorrei capire perché accade e anche se posso usare

Thread.sleep(sometime); 

Edit: -

File x = new file("x.txt"); 
new class1().method1(); 

Dopo la creazione di tutti i file (5), ho solo aggiunto questa linea

x.deleteOnExit(); y.deletOnExit() and so on... 

Tutti i file tranne quello scorso vengono cancellati.

+2

Dovrai aggiungere il tuo codice. Il problema potrebbe esserci. –

+0

Hai appena terminato il processo Java? –

+0

Un modo migliore per gestirlo consiste nell'utilizzare i finalizzatori ... –

risposta

14

assicurarsi che qualsiasi cosa i flussi sono iscritto al file sono chiusi. Se lo stream non viene chiuso, il file verrà bloccato e l'eliminazione restituirà false. Quello era un problema che avevo. Speriamo che questo aiuti.

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.StringWriter; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Date; 
import java.util.List; 


public class Test { 

    public static void main(String[] args) { 

     File reportNew = null; 
     File writeToDir = null; 

     BufferedReader br = null; 
     BufferedWriter bw = null; 
     StringWriter sw = null; 

     List<File> fileList = new ArrayList<File>(); 

     SimpleDateFormat ft = new SimpleDateFormat("yyyymmdd_hh_mm_ss_ms"); 


     try { 

      //Read report.new file 
      reportNew = new File("c:\\temp\\report.new"); 

      //Create temp directory for newly created files   
      writeToDir = new File("c:\\temp"); 
      //tempDir.mkdir(); 

      //Separate report.new into many files separated by a token 
      br = new BufferedReader(new FileReader(reportNew)); 
      sw = new StringWriter(); 
      new StringBuilder(); 



      String line; 
      int fileCount = 0; 

      while (true) { 

       line=br.readLine(); 

       if (line == null || line.contains("%PDF")) { 

        if (!sw.toString().isEmpty()) { 

         fileCount++; 

         File _file = new File(writeToDir.getPath() 
              + File.separator 
              + fileCount 
              + "_" 
              + ft.format(new Date()) 
              + ".htm"); 

         _file.deleteOnExit(); 
         fileList.add(_file); 


         bw = new BufferedWriter(new FileWriter(_file)); 
         bw.write(sw.toString()); 

         bw.flush(); 
         bw.close(); 
         sw.getBuffer().setLength(0); 

         System.out.println("File " 
              + _file.getPath() 
              + " exists " 
              + _file.exists()); 
        } 

        if (line == null) 
         break; 
        else 
         continue; 
       } 

       sw.write(line); 
       sw.write(System.getProperty("line.separator")); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if (bw != null) { 
       try { 
        bw.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 
+1

Probabilmente sarebbe utile illustrare il tuo punto con il codice – beresfordt

2

Per chiudere il file che è stato aperto nel programma, provare a creare un metodo di terminazione esplicito.

Pertanto, provare a scrivere il seguente:

public class ClassThatUsesFile { 

    private String filename; 
    private BufferReader reader; 

    public ClassThatUsesFile (String afile) { 
     this.filename = afile; 
     this.reader = new BufferReader(new FileReader(afile)); 
    } 

    // try-finally block guarantees execution of termination method 

    protected void terminate() { 
     try { 
      // Do what must be done with your file before it needs to be closed. 
     } finally { 
      // Here is where your explicit termination method should be located. 
      // Close or delete your file and close or delete your buffer reader. 
     } 
    } 

} 
-7

Nessun problema. deleteOnExit() funziona per me come un fascino.

File file = new File(UUID.randomUUID().toString() + ".html"); 
file.deleteOnExit(); 

// open file here 

// process file here 

// flush/close file here