0

I am moving data from a file to database then I want to delete a file from which we have extracted the data from a folder in java, I am trying delete command but its not working please help.

5 Answers5

2

Using the Files Class: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html

try {
   Files.delete(path);
} catch (NoSuchFileException x) {
    System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
    System.err.format("%s not empty%n", path);
} catch (IOException x) {
    // File permission problems are caught here.
    System.err.println(x);
}

If you want the process to fail quietly, consider using deleteIfExists

https://docs.oracle.com/javase/tutorial/essential/io/delete.html

JamesB
  • 7,774
  • 2
  • 22
  • 21
1

If you post the code you use you may get better help...

Anyway, are you closing the stream before trying to delete the file?

When you read the file the you must close the stream before you delete it from filesystem.

Something like this

    InputStream in = null;
    File  file  = new File(yourfilepath);
    try{
        in = new FileInputStream(file);
      //do what you need with the content
    }finally{                
        if( in != null ) try {
            in.close();
         } catch( IOException ioe ){}
    }
//NOW YOU CAN DELETE
    file.delete();
Jkike
  • 807
  • 6
  • 12
  • This should be a comment. – JamesB Aug 06 '15 at 07:51
  • Sorry, I don't understand... Why it should be a comment? I think the problem is that he is not closing the file he just read before deleting it. Do I always have to but "code" in the answer to make it an answer? Anyway I add the code – Jkike Aug 06 '15 at 07:56
0

You can use the class File to delete.
Example:

File file = new File("pathFile");
file.delete();
Adrian
  • 60
  • 5
0
File file = new File("test.log");
file.delete();
mherbert
  • 515
  • 3
  • 12
0

File.delete() does what you want.

File fileToDelete = new File(...);
if (fileToDelete.delete()) {
    //successful deleting
} else {
    //it didn't work
}
darijan
  • 9,725
  • 25
  • 38