Re: systematic file(s) deletion
"NickName" <dadada@rock.com> wrote in message
news:1166561571.470451.165900@i12g2000cwa.googlegroups.com...
Hi,
Say, I have a bunch of files sitting under C:\Program
Files\ThisProgram\DataFiles directory,
and I'm running out of disk space, so, I'd like to sysmatically remove
all the file that is more than two days old under this directory. How
would I do that?
Please work with me through the following semi-code.
// first, need to point to/move to this directory, how?
/*
There's this method to find out current directory,
System.getProperty("user.dir");
is there any method that would set current directory such as
System.setProperty("user.dir") = "C:\Program
Files\ThisProgram\DataFiles"; ??
*/
The concept of a "current" directory isn't well defined in Java,
possibly because it isn't well defined across all the OSes that Java
supports. If you wanted to make this an actual utility for users to use,
best to have the user provide the path to the directory they want to operate
on as a command line argument or something similar.
...
// now, we're ready to instantiate the directory
File dir = new File("MyDirectoryName");
// use var children as file names, use array to store them
String[] children = dir.list();
// validation
if (children == null) {
// Either dir does not exist or is not a directory
} else {
// some sort of preparation
int c = 0;
Date today = new Date();
// iteration of files
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
// debug to display files
System.out.println(filename);
// find each file's date/time stamp
// var c for file counter, increment it
c++;
// could we use dynamic var name like "file"&c where "file" is
string and c is var value?
No, you can't use "dynamic var names" in the way that you described. The
closest thing I can think of to what you're trying to do is to use an array.
But a simpler way would be to not keep around a reference to every file
you're going to work with, but rather to just keep a reference to the single
file you're currently working with at that time.
File "file"&c = new File(filename);
long "file"&c&"date = "file"&c.lastModified;
File doesn't have a publicly accessible "lastModified" field, but it has
a lastModified() method which you can invoke.
/* now compare each file's date stamp against today's date if
it's two days old delete it,
DatePart? How to? */
Numerical comparison is typically done via the >, >=, ==, !=, =< and <
operators.
...
// delete file
boolean del = (new File("file"&c)).delete();
}
}
Better way? Many thanks in advance.
This is probably a dangerous program to learn Java with, since you might
mistakenly delete data that you don't want to delete by accidentally
introducing bugs into your program. Why not write a less destructive program
for the purposes of learning? Maybe one that merely *lists* all files older
than a certain age, and leaves it up to the user to manually delete them?
- Oliver