import java.util.Scanner; // bring in Scanner class so we can use it import java.io.*; public class Files /** This class Introduces Files **/ // input files: program reads data from these files // output files: program will store data in these files { public static void main(String[] args) throws IOException { // Program can create an output file // create an object to represent a file on disk // this will delete the file if it previously exists PrintWriter outfile = new PrintWriter("data.txt"); // this object can be used the same way you use System.out for (int i=1; i<10; i++) outfile.println(i); // when done, close the file outfile.close(); // can use a String object to hold filename Scanner keyboard = new Scanner(System.in); System.out.println("What is the name of your output file?"); String filename = keyboard.next(); outfile = new PrintWriter(filename); outfile.println("Hello World!"); outfile.close(); // READING IN DATA FROM A FILE // First, create a File object that represents input file File myfile = new File("data.txt"); /* Then, get a scanner object, but instead of connecting it to the * keyboard (System.in) I will connect it to a File object */ Scanner infile = new Scanner(myfile); int num; for (int i=1; i<10; i++) { num = infile.nextInt(); System.out.println("num in file is: " + num); } infile.close(); } }