import java.io.*;
class files1
{
public static void main(String args[])throws NullPointerException
{
String dirname="c:/test";
File f=new File(dirname,"work.txt");
File f3=new File(dirname,"renfile.txt");
System.out.println("File name is:"+f.getName());
System.out.println("path of file is:"+f.getPath());
System.out.println("parent directory is:"+f.getParent());
System.out.println("listing the contents of directory");
File f1=new File(dirname);
String s[]=f1.list();
for(int i=0;i%26lt;s.length;i++)
{
File f2=new File("\t"+dirname+"/"+s[i]);
if(f2.isDirectory())
{System.out.println("\t"+s[i]+"is a directory");
}
else
{
System.out.println("\t"+s[i]+"is a file");
}
}
}
}
output:
File name is:work.txt
path of file is:c:\test\work.txt
parent directory is:c:\test
listing the contents of directory
Exception in thread "main" java.lang.NullPointerException
at files1.main(files1.java:15)
How to list the contents of the directory.i tried following program.but it throwed run-time exception.?
This command is the culprit:
File f2=new File("\t"+dirname+"/"+s[i]);
1st problem: you create a wrong path. f2 will be null, because the path doesn't make sense. Replace "\t" with File.separator
2nd problem: you use a inefficient way to list directories.
you use list() that returns array of Strings.
use instead listFiles(). It returns an array of file objects and you don't need to reconstruct the string paths.
so your code should change to something like this:
File files[]=f1.list();
for(int i=0;i%26lt;files.length;i++)
{
File f2=new File(files[i]);
if(f2.isDirectory())
{System.out.println(f2.getAbsoluteName... + "is a directory");
}
else {.....}
good luck :)
Reply:/**** updating ****/
Well, I looked closer and it seems like the statement File f2=new File("\t"+dirname+"/"+s[i]); is not correct. Why are you adding a tab character (\t) at the beginning of the file name?
/******************/
I have very little knowledge in Java and haven't coded in it since the last 5 years, but from your code it looks like the File object f1 is NULL because the directory path is incorrect.. should be c:\test instead of c:/test (this is Windows, not Unix). My guess is f1.list() is throwing the exception as f1 is NULL.
Hope this helps. But try to debug your program first before asking others. The problem might be very simple.. you'll know once you debug your code. Also, I don't think this is a very good place to ask questions like this. You should try newsgroups like comp.lang.java.programmer. You will be able to access them through groups.google.com.
Reply:type in... I love pie
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment