Tuesday, April 16, 2013

File View program

The File View program is able to display all files and sub-directories, only files, only sub-directories, or files that have a specific extension in a directory. The program firstly displays a menu that has four choices  as you see in the image below.  With the File View program, you might learn the followings about Java:
-using switch case statement for multiple choices problem,
-using the File class to show files and folders in a computer system directory, and
-filtering files by using the FilenameFilter interface.

FileView source code:

1 import java.io.*;
2 import java.util.Scanner;

class FileView{
3          String dirpath;

4          public static void main(String[] args){
                        int choice;
                        FileView ff=new FileView();
                        ff.showChoices();
                        Scanner sc=new Scanner(System.in);               
                        System.out.print("Enter your choice:");
                        choice=sc.nextInt();
                        switch(choice){
                                                case 1: ff.showAll();break;
                                                case 2: ff.showOnlyFiles();break;
                                                case 3: ff.showOnlyDirectories();break;
                                                case 4: ff.showFileWithExt();break;
                                                default: System.out.println("Invalid choice");
                                    }
                                   
                       
            }

5          public void showAll(){
                                   
                                                String[] allfiles=getFiles(false);
                                                if(allfiles.length>0) {
                                                            for(String item:allfiles)
                                                                        System.out.println(item);    
                                                            }
                                   

                                   
                                   
                        }

6          public void showOnlyFiles(){
                                                String[] onlyFiles=getFiles(false);
                                                if(onlyFiles.length>0) {
                                                            for(String item:onlyFiles){
                                                                        File f=new File(dirpath+"/"+item);
                                                                        if(f.isFile())
                                                                                    System.out.println(item);
                                                                       
                                                                        }          
                                                            }
                                                                       
                        }

7          public void showOnlyDirectories(){
                                   
                                                String[] onlyDirs=getFiles(false);
                                                if(onlyDirs.length>0) {
                                                            for(String item:onlyDirs){
                                                                        File d=new File(dirpath+"/"+item);
                                                                        if(d.isDirectory())
                                                                                    System.out.println(item);
                                                                       
                                                                        }          
                                                            }
                                                                       
                                   
                        }

8          public  void showFileWithExt(){
                                   
                                    String[] filesWithEx=getFiles(true);
                                    if(filesWithEx.length>0) {
                                                            for(String item:filesWithEx)                                                                                                                                                                                                                                                                                                            System.out.println(item);                                                    
                                                                                   
                                                            }
                                   

            }
           
9          public String[] getFiles(boolean withSpecificExt){
                                    BufferedReader br=null;   
                                    File file=null;                        
                                    String[] files=null;
                                    try{
                                                br=new BufferedReader(new InputStreamReader(System.in));
                                                System.out.print("Directory path (e.g D:/test/):");
                                                dirpath=br.readLine();
                                                file=new File(dirpath);
                                                           
                                                if(withSpecificExt==false)
                                                            files=file.list();
                                                           
                                                else{
                                                            System.out.print("File extension (e.g. txt):");
                                                            String extension=br.readLine();
                                                            Ext ex=new Ext(extension);
                                                            files=file.list(ex);
                                                }
                                                br.close();
                                   
                                    }catch(Exception ie){System.out.println("Error...");}

                                    return files;
                                               
                        }

10        public static void showChoices(){
                        System.out.println(".....................................");
                        System.out.println("Files and Directories View");
                        System.out.println(".....................................");
                        System.out.println("1. Show all files and directories");
                        System.out.println("2. Show only files");
                        System.out.println("3. Show only directories");
                        System.out.println("4. Show all files with a specific extension");
                       
            }
           
11        public class Ext implements FilenameFilter{
                        String ext;
                        Ext(String extension){
                                    ext="."+extension;
                        }
                        public boolean accept(File dir, String name){
                                    if(name.endsWith(ext)) return true;
                                    else return false;     
                        }
            }
           
}

File View program in Java


Code Explanation:

1 Introduce the io package to the program. This package is useful as its contains some classes that are needed to get user input from keyboad (e.g BufferedReader, File,...) and to navigate through a directory.
2 Introduce the Scanner class to the program. The Scanner class has the nextInt method that the program uses to receive numerical choices from the keyboard.

3 The class variable dirpath is used to store the directory path input by the user.

4 The program begins from the main method. When the program starts, the FileView ff is create so that its methods can be invoked to perform their tasks. To display the program menu of choices, the showChoices method is invoked. The Scanner sc object is created to receive the choice input by the user. The switch case statement is used to detect the choice and do task accordingly.

5 The showAll method has code to show all files and folders. This method is invoked by the main method when the choice is 1. The showAll method invokes the getFiles method to retrieve all files and folders in a directory that input by the user and stores those files and directories in the allFiles array of string. Then the foreach loop is used to print all those file and folder name on the console window.

6 The showOnlyFiles method has code to show only the files in the directory input by the user. The getFiles method is invoked to get a list of files and sub-directories. To display only the files in that directory, the method isFile is used. The isFile method returns true to indicate that the file object is really a file.  If the isFile returns true the file name is printed on the console window. Otherwise, it is not printed.

7 The showOnlyDirectories method has code to show only the sub-directories in the directory input by the user. The getFiles method is also invoked to get a list of files and sub-directories. The isDirectory method is used to check whether the file object is a directory before the its name is displayed.

8 The showFileWithExt method has code to show only the files that have a specific extension input by the user. To filter the file names based on their extension, the FilenameFile interface is used. 

9 The getFiles method is invoked by the four method above. The getFiles method has code to retrieve all files, or sub-directories from a directory by using the list() method of the file object. This method has one boolean argument--withSpecificExt. If withSpcificExt argument has the true value, it is an indication that the user wants to show files with a specific extension. This case happens when the choice is 4. Otherwise, it is the case for choice 1, 2, or 3.

10 The showChoice has code to show a menu of choices to user.

11 The class Ext implements the FilenameFile interface. This interface has the accept(File dir, String name) method to filter file names based on its extension. The object of Ext class is created and used in the case that the user wants to show the files that has a specific extension.

1 comment:

  1. It is nice article to improve my knowledge.thank you for sharing useful post
    visit
    web programming tutorial
    welookups

    ReplyDelete