Java Reference
In-Depth Information
1
import java.io.File;
2
3
public class FileSystem
4
{
5
// Output file name with indentation
6
public static void printName( String name, int depth )
7
{
8
for( int i = 0; i < depth; i++ )
9
System.out.print( " " );
10
System.out.println( name );
11
}
12
13
// Public driver to list all files in directory
14
public static void listAll( File dir )
15
{
16
listAll( dir, 0 );
17
}
18
19
// Recursive method to list all files in directory
20
private static void listAll( File dir, int depth )
21
{
22
printName( dir.getName( ), depth );
23
24
if( dir.isDirectory( ) )
25
for( File child : dir.listFiles( ) )
26
listAll( child, depth + 1 );
27
}
28
29
public static long size( File dir )
30
{
31
long totalSize = dir.length( );
32
33
if( dir.isDirectory( ) )
34
for( File child : dir.listFiles( ) )
35
totalSize += size( child );
36
37
return totalSize;
38
}
39
40
// Simple main to list all files in current directory
41
public static void main( String [ ] args )
42
{
43
File dir = new File( "." );
44
listAll( dir );
45
System.out.println( "Total bytes: " + size( dir ) );
46
}
47
}
figure 18.10
Java implementation
for a directory listing
Search WWH ::
Custom Search