next up previous
Next: Packages Up: I/O, I/O, it's off Previous: Keyboard & Display I/O

File I/O

A simple file I/O example:


import java.io.*;                                                                                          

/* This class is an example of opening a file for output, writing something to
     the file, and then closing the file 
*/
class Test{
    private static BufferedReader in;
        public static void main(String[] args) throws IOException{
           PrintStream out = new PrintStream(new FileOutputStream("testout.txt"));
            out.println("This is output to file");
            System.out.println(``This is output to the display'');
            out.flush();
            out.close();
        }
}

A more complicated file I/O example:


import java.io.*;
class Test{

    private static BufferedReader in;
    private static PrintStream out;
    private static PrintStream outtemp;

    private static void readKeyboard(){
            InputStreamReader k = new InputStreamReader(System.in);
            in = new BufferedReader(k);
    }

    private static void readFile(String fname) throws IOException{
	    in = new BufferedReader(new FileReader(fname));
    }

    private static void fileOutput(String fname) throws IOException{
	    out = new PrintStream(new FileOutputStream(fname));
    }	
	
    private static void changeOut(PrintStream oldout, PrintStream newout){
	outtemp = oldout;
	System.setOut(newout);
    }

    private static void cleanUp(PrintStream toclean){
	toclean.flush();
	toclean.close();
    }

    
        public static void main(String[] args) throws IOException{

	    readKeyboard();

            String il = in.readLine();
            System.out.println("il = " + il);

	    fileOutput("output.txt");
	    out.println("This is output to file");

	    changeOut(System.out, out);
            System.out.println("il = " + il);

	    changeOut(out, outtemp);
	    cleanUp(out);

	    readFile("output.txt");
	    String x = in.readLine();
	    String y = in.readLine();

	    System.out.println("\n" + "Stuff from file:" +"\n" + x + "\n" + y + "\n");

	    in.close();
        }
}

More stuff coming soon...



Chris Trendall
Copyright ©Chris Trendall, 2001. All rights reserved.

2001-12-09