Rechercher
 

Classe java.io.File

La classe File permet de manipuler certaines informations relatives au fichier spécifié. L'exemple ci-dessous liste, de manière récurssive, le contenu du dossier spécifié en paramètre.

 1 
 2 
 3 
 4 
 5 
 6 
 7 
 8 
 9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

public class Listing {    
    
    public static void scanDirectory( File currentDirectory, String level )
            throws IOException {
        for( File file : currentDirectory.listFiles() ) {
            char type = file.isDirectory() ? 'd' : '-';
            long length = file.length() / 1024;
            Date lastModifiedDate = new Date( file.lastModified() ); 
            DateFormat dateFormatter = 
                    DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT );
            String lastModifiedString = dateFormatter.format( lastModifiedDate );            

            System.out.printf( "%c %10d ko %18s %s%s\n", 
                    type, length, lastModifiedString, level, file.getName() );

            if ( file.isDirectory() ) {
                Listing.scanDirectory( file, level + "    " );
            }
        }        
    }

    public static void main(String[] args) throws IOException {
        String workingDirectory = ".";
        if ( args.length > 0 ) {
            workingDirectory = args[0];
        } 

        File workingDirectoryFile = new File( workingDirectory );
        if ( ! workingDirectoryFile.exists() ) {
            System.err.println( "The specified directory not exist" );
            System.exit( -1 );
        }
    
        if( ! workingDirectoryFile.isDirectory() ) {
            System.err.println("The specified path is not a directory");
            System.exit( -1 );
        }
        
        System.out.println( "Listing of " +
                workingDirectoryFile.getCanonicalPath() );    
        Listing.scanDirectory( workingDirectoryFile, "" );
    }
}
Listing du contenu d'un dossier