Denisowator Denisowator - 27 days ago 4x
Java Question

How to target directories and delete files?

I've been learning JavaScript for 4 weeks now at college, and I've starting learning Java 2 weeks ago in my own time. It proved useful as we have a project, where we have to make a program (that's what we chose for the project anyway).

The problem is, while I know most of the fundamentals of Java, I don't know enough to make the program we want to make, and all my other team members have never even touched Java, and some are even struggling with JavaScript in class.

Sorry for the rambling btw, I just want to make sure people understand where I'm coming from.

Anyway, we decided to make a program that is similar to the disk cleanup function in the Windows Control Panel. As in, it deletes temporary and unnecessary files to free up space.

And I have no idea how to even begin coding something like that. I'm not asking anyone to do the whole coding for me, but I need to quickly learn how to make a program that targets listed directories, and then deletes specific or all files from that directory. So for example, the first thing I would need it to target is the "Temp" folder in the Windows folder, and then delete all the files and any sub-folders in it.

How would I do this?

Also, this is my first time ever posting a question on Stack Overflow, and I've been really overwhelmed with the amount of really complex things being asked left and right, and I was holding off on asking this, because I feel like if I ask something very simple, and don't put in a huge block of complex code with my question, I'm gonna get terminated or something.


For getting the temporary directory, you can refer to this post, which indicates it is this:


Also, for how to deal with file manipulation, I suggest you read the java documentation found here.

For example, that link indicates that to delete a File, you might be interested in the method:

public boolean delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

true if and only if the file or directory is successfully deleted; false otherwise

SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file

I'd also reccommend you search around and look for some examples, as will as read relevant portions of the online Javadocs.

Also, I can speak from experience that deleting files can be a bit messy if you do not know what you are doing. Beforing trying that, you might want to really make sure you know what you are doing.