import java.io.File; import java.io.FileInputStream; import java.io.PrintStream; import java.io.FileNotFoundException; import java.util.Scanner; /** File.java - Experiment with opening, reading, and writing files. * This is a simple empirical study of the file and memory systems. * We are curious how long things take and how much space is occupied. * In Java's System class there is a useful method called currentTimeMillis, * which allows us to measure time to the nearest millisecond. */ public class Files { public static void main(String [] args) throws FileNotFoundException { long t1 = System.currentTimeMillis(); // Experiment #1: Write a loop that creates 1000 empty files. // The files should be placed into a subfolder called dummy. // Let's call the files 1.txt thru 1000.txt. // To create a file, call the PrintStream constructor. Then immediately // close the file, so that you are ready to create the next file. /******************* write your loop here ********************/ long t2 = System.currentTimeMillis(); long diff = t2 - t1; System.out.printf("File creations took %d ms.\n", diff); // Experiment #2: Mwa-ha-ha-ha, time to delete! // Use the delete() method in the File class in the Java API. File dir = new File("dummy"); File [] list = dir.listFiles(); t1 = System.currentTimeMillis(); /******************* write your loop here *******************/ t2 = System.currentTimeMillis(); diff = t2 - t1; System.out.printf("File deletions took %d ms.\n", diff); // Create one dummy file for the next experiment. PrintStream bigFile = new PrintStream("big.txt"); t1 = System.currentTimeMillis(); // Experiment #3: Write 100 MB to one file. How long will it take? // To reduce the loop overhead, write a loop with 1 million iterations. // On each iteration, write a 100-character string literal to the file. /******************** write your loop here *******************/ t2 = System.currentTimeMillis(); bigFile.close(); diff = t2 - t1; System.out.printf("Writing 100 MB took %d ms.\n", diff); // Experiment #4: Now, let's read the file. Scanner in = new Scanner(new FileInputStream("big.txt")); t1 = System.currentTimeMillis(); /********************* write your loop here ******************/ t2 = System.currentTimeMillis(); in.close(); diff = t2 - t1; System.out.printf("Reading 100 MB took %d ms.\n", diff); // Experiment #5: Delete the big file. t1 = System.currentTimeMillis(); File f = new File("big.txt"); /**************** Tell Java to delete the file **************/ t2 = System.currentTimeMillis(); diff = t2 - t1; System.out.printf("Deleting a 100 MB file took %d ms.\n", diff); } }