1

I am working on one project in which I use java.nio.* for file operation. Basically my product is working on server now I am creating files on server using Java 7.

Files.createFile(path)//For creating file.

But when I want to delete it using

Files.delete(path)

it gives me message

The process cannot access the file because it is being used by another process.**

Delete file code ....

Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file,
                    BasicFileAttributes attrs) throws IOException {

                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException e)
                    throws IOException {
                if (e == null) {
                     Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    // directory iteration failed
                    throw e;
                }
            }

        });
vaibhav makwana
  • 153
  • 1
  • 10
  • possible duplicate of [Java 7: Path vs File](http://stackoverflow.com/questions/6903335/java-7-path-vs-file) –  Jul 26 '12 at 13:11
  • You probably leave the file open after you write to it somewhere in your code. Remember to always close files/streams/etc. after you're done with them. Java 7 provides a neat mechanism called 'try with resources' that takes care of that for you: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html I'm afraid nothing more can be said unless you provide more info. – toniedzwiedz Jul 26 '12 at 13:13

4 Answers4

4

You cannot delete a file which has been locked by your process or another process. On windows, files are locked by default, on linux they have to be lock explicitly.

This example

Path path = FileSystems.getDefault().getPath("test.log");
Path file = Files.createFile(path);
Files.delete(file);

runs with out error

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

To delete a file, you must obtain the file handler (normally owned by the thread which created it). Thus, If one thread created a file, another thread CANNOT delete it.

Make sure, when you delete your file, the server didn't create another thread which is what happens on each server code.

PS: If you want more a better answer, you will have to provide more info

Adel Boutros
  • 10,205
  • 7
  • 55
  • 89
0

Did you close all your writers that use the reference to the given file?

Kurt Du Bois
  • 7,550
  • 4
  • 25
  • 33
0

If you are using swing components to open the file, you could use the dispose() method for that component that opens the file.

Winnifred
  • 1,202
  • 1
  • 8
  • 10