I've been stuck on this thing for at least a full month now.
What I have, is a code that specifies a directory, and then checks if the directory is empty. If it's not, it deletes all the files inside it and leaves the directory folder. I'm using this to clean stuff like temporary files, and the recycle bin.
The way I did it, is I declared a variable called "SRC_FOLDER" inside a private method, which has the value of the directory I want cleaned. And then in a public method, I wrote the rest of the code.
Here is the full code:
import java.io.File;
import java.io.IOException;
public class test {
private static final
String SRC_FOLDER = "C:\Users\Denisowator\AppData\Local\Temp";
public static void main(String[] args) {
File directory = new File(SRC_FOLDER);
//Check if directory exists
if(!directory.exists()) {
System.out.println("Directory does not exist.");
System.out.println("Skipping directory.");
System.exit(0);
}
else {
try {
delete(directory);
}
catch(IOException e){
e.printStackTrace();
System.exit(0);
}
}
System.out.println("Cleaned directory" + SRC_FOLDER + ".");
}
public static void delete(File file)
throws IOException{
if(file.isDirectory()){
//If directory is empty
if(file.list().length==0){
System.out.println("Directory is empty")
}
}
else {
//If file exists, then delete it
file.delete();
System.out.println("File is deleted : " + file.getAbsolutePath());
}
}
}
As you can see, the variable is used as a value for a file, which is essentially the folder I want cleaned, it then checks the file's length (amount of files inside it), and if the length is above zero, the files are deleted.
It all works fine, but what I have a problem with, is specifying the same directory, based on what user executes the code.
Let's say I give this program to someone, and their name is "Steve" or something like that. The code won't work, because it's looking for a user "Denisowator" in the Users folder. So how can I make the value change, based on what the user's username is?
I've looked into things like "user.home" and "user.dir", but I have no idea how I would implement that into a variable's value.