File.list() method

File.list() method

import java.io.*; class xyz { public static void main(String[] args){

    byte b[]=new byte[5000];
    System.out.println("enter the path name");
    try{
  System.in.read(b);
    }catch(Exception e)
    {}
     String s2=new String(b);


   File f1=new File(s2);
  String [] a=f1.list();
  System.out.println(a.length);
  for(int i=0;i<a.length;i++)
  {
      System.out.println(a[i]);
  }
    }

} in the above question if i enter path name as d:/java it is giving NullPointerException.

but if I directly write code like- File f1=new File("d:/java"); instead of File f1=new File(s2);and then call list() method then it is working fine although s2 also prints as "d:/java" ?? help

View Answers

July 31, 2012 at 11:36 AM

Here is an example of File.lsit() method. The given code accepts the directory path in order to display the files and directories of that directory.

import java.io.*;
import java.util.*;
class xyz {
    public static void main(String[] args){
    Scanner input=new Scanner(System.in);
    System.out.print("Enter file path: ");
    String str=input.nextLine();
    File f=new File(str);
    String files[]=f.list();
    for(int i=0;i<files.length;i++){
        System.out.println(files[i]);
    }
    }
}









Related Tutorials/Questions & Answers:

Ads