cheese5505
cheese5505

Reputation: 982

File won't remove

I am trying to remove a file in java, but it will not remove. Could someone explain why it won't remove?

Here is the code that I am using:

File bellFile = new File("config\\normbells.txt");

bellFile.delete();

File bellFileNew = new File("config\\normbells.txt");

bellFileNew.createNewFile();

System.out.println("Done!");

NOTE: I am trying to wipe the file, if that helps.

Upvotes: 0

Views: 512

Answers (3)

RAS
RAS

Reputation: 8158

File deletion can fail under the following circumstances:

  1. The file does not exist.
  2. The file is a directory not a file.
  3. You don't have access to delete the file.
  4. You don't have access to the the file or any of its parent directory.
  5. The file is being used currently by some another application.

Try avoiding all the above mentioned circumstances & you'll surely able to delete the file. Also before deleting the file add this condition :

if (file.exists()) {
    file.delete();
}

Upvotes: 2

David
David

Reputation: 20063

Java7 has new functionality for this.

Path target = Paths.get("D:\\Backup\\MyStuff.txt");
Files.delete(target);

Path newtarget = Paths.get("D:\\Backup\\MyStuff.txt");
Set<PosixFilePermission> perms
    = PosixFilePermissions.fromString("rw-rw-rw-");
FileAttribute<Set<PosixFilePermission>> attr
    = PosixFilePermissions.asFileAttribute(perms);
Files.createFile(newtarget, attr);

Take a look at the File class http://docs.oracle.com/javase/7/docs/api/java/io/File.html

Upvotes: 1

PermGenError
PermGenError

Reputation: 46398

File bellFile = new File("config\\normbells.txt");
if(bellFile.delete())
{
System.out.println("Done!");
}

Upvotes: 0

Related Questions