Console IO | File IO |
---|---|
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); |
BufferedReader fileIn = new BufferedReader(new FileReader(filename)); |
PrintWriter stdOut = new PrintWriter(System.out, true); |
PrintWriter fileOut = new PrintWriter(new FileWriter(filename)); |
// reading from console int x = Integer.parseInt(stdIn.readLine()); |
// reading from a file int x = Integer.parseInt(fileIn.readLine()); |
// writing to console stdOut.println(5); |
// writing to a file fileOut.println(5); |
PrintWriter fileApnd = new PrintWriter(new FileWriter(filename, true);
import java.io.*; /** * Sample program: Copy * * Makes a copy of a file. * * @author Sean Bufano * @version 1.1 */ public class Copy { /* input object for console input */ private static BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); /* output object for normal console output */ private static PrintWriter stdOut = new PrintWriter(System.out, true); /* output object for alternative console output */ private static PrintWriter stdErr = new PrintWriter(System.err, true); /** * Main program * * @param args not used * @throws IOException */ public static void main(String[] args) throws IOException { BufferedReader inFile = getFileForReading("Source filename: "); PrintWriter outFile = getFileForWriting("Destination filename: "); try { String line = inFile.readLine(); while (line != null) { outFile.println(line); line = inFile.readLine(); } } catch (Exception e) { } finally { inFile.close(); outFile.close(); } } /** * opens a file for reading * * @param message message used as prompt * @return a reference to the file * @throws IOException */ private static BufferedReader getFileForReading(String message) throws IOException { do { try { stdErr.print(message); stdErr.flush(); return new BufferedReader(new FileReader(stdIn.readLine())); } catch (FileNotFoundException fnfe) { stdErr.println(fnfe.toString()); } } while (true); } /** * opens a file for writing. * * If file exists, its contents are erased. * * @param message message used as prompt * @return a reference to the file * @throws IOException */ private static PrintWriter getFileForWriting(String message) throws IOException { stdErr.print(message); stdErr.flush(); return new PrintWriter(new FileWriter(stdIn.readLine())); } /** * opens a file for appending. * * @param message message used as prompt * @return a reference to the file * @throws IOException */ private static PrintWriter getFileForAppending(String message) throws IOException { stdErr.print(message); stdErr.flush(); return new PrintWriter(new FileWriter(stdIn.readLine(), true)); } }
Previou page | Next page |