Wednesday, July 3, 2013

File

Java provides File class that can be used to manage files and directories. Its constructor is File(String filepath). The useful methods of the File class are shown below:

-canRead() method tests whether the file can be read.
-canWrite() method tests whether the file can be modified.
-exists() method tests whether the file or directory exists.
-isFile() method tests whether the file denoted by the pathname is a normal file.
-isDirectory() method tests whether the file denoted by the pathname is a directory.
-delete() method deletes the file or directory. It returns true if deletion is successful. To delete a directory, it must be empty.
-createNewFile() method create a new file.
-length() method returns the length of the file in byte.
-mkdir() method creates a new directory.
-mkdirs() method creates a directory and its parent directories.
-list() method returns an array of string filenames and directory names.
-list(FilenameFilter filter) methods returns an array of string filenames that matches the filter.
-renameTo(File obj) method renames the file to another one specified as the File obj argument.

Example: show file and directory names in drive d:

import java.io.File;
public class FilesShow{

public static void main(String[] args){

showFiles("d:/");

}

public static void showFiles(String dir){

File f=new File(dir); //create file object to connect to the directory
if(!f.exists()){
System.out.println("Source directory does not exist.");
System.exit(-1);
}
else if(!f.isDirectory()){
System.out.println("It is not a directory.");
System.exit(-1);
}

String[] filenames=f.list(); //list file and directory names
for(String name:filenames){

System.out.println(name);

}


}



}

No comments:

Post a Comment