Basic file I/O notes import java.io.*; // for I/O import java.util.*; // for Scanner class add "throws IOException" to methods that use file I/O (or use try/catch blocks) Scanner infile = new Scanner(new FileReader(filename)); // to read a file String s1 = infile.nextLine(); // reads a String from infile int n1 = infile.nextInt(); // reads an integer from infile double d1 = infile.nextDouble(); // reads a double from infile PrintWriter outfile = new PrintWriter(filename); // to write a file outfile.println(n); // writes the value of n to outfile
Sample code Write items to file and then read them: import java.io.*; import java.util.*; public class TestFile1 { public static void main(String[] args) throws IOException { PrintWriter outfile = new PrintWriter("stuff.txt"); int year = 2017; double bodyTemp = 98.6; outfile.println("CIS 160"); outfile.println("Kishwaukee College"); outfile.println(year); outfile.println(bodyTemp); outfile.close(); Scanner infile = new Scanner(new FileReader("stuff.txt")); System.out.println(infile.nextLine()); System.out.println(infile.nextLine()); System.out.println(infile.nextInt()); System.out.println(infile.nextDouble()); infile.close(); } } Read from file until done: import java.io.*; import java.util.*; public class TestFile2 { public static void main(String[] args) throws IOException { PrintWriter outfile = new PrintWriter("stuff.txt"); for (int i=1; i<=10; i++) { outfile.println(i*2); } outfile.close(); Scanner infile = new Scanner(new FileReader("stuff.txt")); while (infile.hasNext()) { System.out.println(infile.nextInt()); } infile.close(); } } Read using BufferedReader: import java.io.*; import java.util.*; public class TestFile3 { public static void main(String[] args) throws IOException { PrintWriter outfile = new PrintWriter("stuff.txt"); outfile.println("Kishwaukee College"); for (int i=1; i<=10; i++) { outfile.println(i*2); } outfile.println("CIS 160"); outfile.close(); BufferedReader infile = new BufferedReader(new FileReader("stuff.txt")); // All input treated as a String String lineIn; while ((lineIn = infile.readLine()) != null) { System.out.println(lineIn); // Note: Need Integer.parseInt(lineIn) to treat input as integer } infile.close(); } }
Sample programs see FileOutput.java see FileInput.java see FileOutput2.java: modified to output more data see FileInput2.java: uses Scanner object to read file see BasicFileTest.java see BasicFileTest2.java
Resources Note: The David J. Eck text goes into much more detail and covers much more than we need for this course. Streams, Files, and Networking (overview) Streams, Readers, and Writers Files Programming With Files