PDA

Click to See Complete Forum and Search --> : [RESOLVED] Java - Get list of files in C:\Windows directory


Giftx
Apr 20th, 2008, 11:51 AM
Hi everyone.
I am just finding my way into java programming world. Can anyone please show me a sample code to list the items in my C: directory; such as:
list of file names, their sizes/length etc?

presently this is how far I've gone:


import java.lang.*;
import java.lang.String.*;
import java.io.*;
import java.io.File;


public class ListDirContents
{
//Define variables
//----------------

int i;

String flname;

String flsize;

//create new instance of File
//---------------------------

File newfile = new File("C:/WINDOWS");

String filelist[] = newfile.list();

}

public class WriteDirContents Extends ListDirContents
{
public static void main (String[] args) throws ioException
{

for(i=0;i<filelist.length;++i) // Print out all files
{
flname = filelist.getName();

System.out.println("The file name is: " + flname);

flsize = filelist.getLength();

System.out.println("The file size is: " + flsize);
}
}

}



Any assistance will be greatly appreciated.
GiftX.

ComputerJy
Apr 20th, 2008, 05:01 PM
The next time you post your code on the web, please make sure it works before posting. Anyway, I've got rid of some useless variables and added the iterative feature. Hope this helps

import java.io.File;

public class Util {

public static void main(String[] a) {
System.out.println("Scouting folder: " + "C:\\Windows");
listFiles("c:/windows", true);
}

private static void listFiles(String root, boolean iterative) {
File[] filesList = new File(root).listFiles();
for (int i = 0; i < filesList.length; ++i) {
if (filesList[i].isFile()) {
System.out.println("File name: " + filesList[i].getName());
System.out.println("\t\tSize = " + filesList[i].length());
} else if (iterative) {
System.out.println("Scouting folder: " + filesList[i].getPath());
listFiles(filesList[i].getPath(), true);
}
}
}
}

ComputerJy
Apr 20th, 2008, 05:02 PM
Oh and by the way, you never need to import java.lang

manavo11
Apr 20th, 2008, 08:08 PM
The next time you post your code on the web, please make sure it works before posting.

If it was working, he wouldn't be posting here asking for help, would he? ;)

ComputerJy
Apr 21st, 2008, 12:08 AM
If it was working, he wouldn't be posting here asking for help, would he? ;)
Good point :p but I meant a code that compiles successfully

Giftx
Apr 21st, 2008, 11:32 AM
Hey 'Jy'.
Thanks for your post. It worked. However, in response to your post, if the code compiles and works would I be posting it? I guess not.

Manavo11, thanks for having my back on the above.

Much appreciation to you all.

GiftX.