hi all!

i want to delete a file/directory in java, the delete().depends on other programs which uses file name as string.but for me to delete the file,the name must be a File.

that is what i have realized as when i use string it does not recognized some methods,like List etc

how can i go about it.
note:
1.the program should not limit to only file but should also delete directory if the thing to be deleted is directory.

2.the file should be deleted despite any security measure like:write protected etc

please help

Recommended Answers

All 5 Replies

well... if you have the name of the file in a String, for instance

String fileName = "input.txt";

take a look at the api's of the File-class. especially take a good look at the constructors.

for deleting that directory, you'll have to use recursivety to first delete all the files in that directory (and any subdirectories)

CLARIFICATION TO STRING TO FILE

bestjew:thanks but.
the program should be able to delete the directory or file from command prompt;you enter the name of the file and it should be able to be deleted.note.the name of the dir/file should not be appearing in the code.
in short,i should be able to create and delete without code modification.
reading an entry from keyboard,the format accepted are string,integer etc but not type file.

Yes you can accept a string as an input and then convert this string to a File type. There is a contructor in the File that allows this.

public class DeleteFile{
    public static void main(String [] args){
        // Pass the first argument which is a filename to the constructor.
        File deleteFile = new File(args[0]);
        // code to delete file goes here.
    }
}

But remember the path you specify on the command line should either be an absolute path or you should be running the program from the same directory, where the file/directory to be deleted exists, for this to work.

EDIT : We would certainly like you doing some homework of your own, it seems you haven't gone through the File class documentation at all.

EDIT : We would certainly like you doing some homework of your own, it seems you haven't gone through the File class documentation at all.

since he/she hadn't even figured out it is possible to get a String from input, either by using Scanner, JOptionPane or as easy as taking arguments from the args array, I doubt simply reading some api's will do the trick there :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.