Page 662 - Introduction to Programming with Java: A Problem Solving Approach
P. 662
628 Chapter 15 Files
/*************************************************
*
FileSizes.java
Dean & Dean
This program displays the names and sizes of
files in the current directory.
*************************************************/
*
*
*
*
import java.io.*;
public class FileSizes
{
}
public static void main(String[] args)
{
}
// end main
File currentDirectory = new File(".");
File[] files = currentDirectory.listFiles();
for (int i=0; i<files.length; i++)
{
}
.classpath
226 bytes
384 bytes
1135 bytes
645 bytes
2058 bytes
2185 bytes
2182 bytes
2659 bytes
.project
System.out.printf("%-25s%6d bytes\n",
files[i].getName(), files[i].length());
// end FileSizes cAlapssago PDF Enhancer Sample output:
FileSizes.class
FileSizes.java
FileSizesGUI.class
FileSizesGUI.java
HTMLGenerator.class
HTMLGenerator.java
Figure 15.13
FileSizes program with sample output
The currentDirectory.listFiles call returns an array of File objects, with one File object for each file in the current directory. Also note this statement:
System.out.printf("%-25s%6d bytes\n",
files[i].getName(), files[i].length());
The format string says to print a left-aligned string in 25 spaces and then print a (right-aligned) floating point number in 6 spaces. The files[i] variable identifies file i in the current directory. The getName call returns the name of file i. The length call returns the size of file i in bytes.