finding a file

I'm trying to locate a general a file on my machine, only knowing its name. Right now I have the code

public static void visitAllDirsAndFiles(File dir) {

if (dir.isDirectory()) {

String[] children = dir.list();

for (int i=0; i<children.length; i++) {

visitAllDirsAndFiles(new File(dir, children));

System.out.println (children);

}

}

And that works perfectly fine for finding out whether the file exists, since it lists everything under the c drive. The problem is, once I change String[] children = dir.list();

to

File [] children = dir.listFiles(); and children to children.getPath();

the program no long compiles. WHY IS this?! I want to find the pathname of the file i'm searching for.

All advice would be appreciated!>

[846 byte] By [nw59a] at [2007-10-2 9:05:10]
# 1
Its as simple as this if you know the name.java.io.File f = new java.io.File("<yourfile.exten>");System.out.println(f.getAbsolutePath());use f.exists() to find out if the file is present.
CjavaVMa at 2007-7-16 23:12:09 > top of Java-index,Java Essentials,Java Programming...
# 2
Wow I wish I thought of that earlier, it could have saved me alot of time. Thanks!
nw59a at 2007-7-16 23:12:09 > top of Java-index,Java Essentials,Java Programming...
# 3

do it like this :

if (dir.isDirectory()) {

String[] children = dir.list();

for (int i=0; i<children.length; i++)

{

if(children.isDirectory())

{

visitAllDirsAndFiles(new File(dir, children));

} else

File f = new File(dir+"/"+children);

String path = f.getAbsolutePath();

System.out.println (children);

}

}>

CjavaVMa at 2007-7-16 23:12:09 > top of Java-index,Java Essentials,Java Programming...
# 4

A more generic (and reusable) solution is to write an abstact class that traverses a directory tree and performs an action (supplied by the implementing class) in each directory. If the implementing class is searching for a file, then it would simply look in the current directory for the specified file name.

If you've got the time, I'd recommend looking as this approach, as you'll learn a lot about various topics (abstract classes, recursion, etc.).

Dick_Adamsa at 2007-7-16 23:12:09 > top of Java-index,Java Essentials,Java Programming...
# 5

OK Here's a Followup question:

Right now, I want to unzip a file. Assume I've already created the unzipping method:

unzipFile (File file_input,)

When I call the unzip method like this:

File f = new File ("Java Notes.zip");

unzipFile (new File (" " + f.getAbsolutePath());

Nothing happens!

but when I call it like this:

unzipFile (new File ("C:\Documents and Settings\Java Notes.zip"));

it unzips properly!

I assume its because when I get the AbsolutePath, it returns the path with the separator ' / ' instead of ' \ '.

So I'm wondering if there's anyway to convert between the two types of separators. THANKS!

nw59a at 2007-7-16 23:12:09 > top of Java-index,Java Essentials,Java Programming...