Can't delete files in java?

后端 未结 5 685
广开言路
广开言路 2021-01-24 11:07

I am trying to delete all files in a folder:-

    import java.io.*;
public class AddService {   
    public static void main(String args[]){
        File folder=         


        
相关标签:
5条回答
  • 2021-01-24 11:36

    There are any number of reasons why a file cannot be deleted; it may not exist, it may be a non-empty directory, you may not have closed all resources using it, and your program may not have permission to do so, to name a few.

    Unfortunately the File.delete() method provides very little information as to why; it's pretty much up to you to poke around and figure it out. But there's good news; you don't want to use File in the first place.

    Java 7 introduced the new java.nio.file package which is a much more robust file access API. It provides the concept of an abstract Path and separates concrete operations into the Files class, in particular it provides Files.delete() which is documented to raise clear exceptions describing the reasons deletion might fail.

    Use Path and Files; you'll be glad you did.

    0 讨论(0)
  • 2021-01-24 11:38

    I figured it out, I was using a FileReader to read contents of the file which I didn't close. Sorry for not providing the entire code

    0 讨论(0)
  • 2021-01-24 11:50

    You have not given the full path for the folder. Also note to use forward slash.

    try{
            File folder=new File("C:/xxxx/xxxx/xxxx/inputs");
            File[] listOfFiles=folder.listFiles();
            for(File file:listOfFiles){
                if(file.delete())
                    System.out.println("File deleted");
                else
                    System.out.println("File not deleted");
            }
    }
    catch(Exception e)
    {
        System.out.println(e.printStackTrace());
    }
    

    Always use try-catch for code that contains methods which throws Exceptions.

    0 讨论(0)
  • 2021-01-24 11:52
    1. Try giving the full path in this statement: "File folder=new File("inputs");"
    2. Use try-catch block and print the exception, if any
    0 讨论(0)
  • 2021-01-24 11:56

    There is nothing wrong with your code except you should give the full path.

    try this : File folder=new File("C:\\inputs");

    instead of this line : File folder=new File("inputs");

    0 讨论(0)
提交回复
热议问题