/************************************************************************* * * Demonstrates writing to a file. * *************************************************************************/ import java.io.*; import java.util.*; public class Write { public static void main (String[] args ) { Scanner infile = null; PrintWriter outfile = null; int counter = 0; try { infile = new Scanner(new File("ReadAndWrite.java")); outfile = new PrintWriter(new BufferedWriter (new FileWriter("out.txt"))); String line; while ( infile.hasNextLine() ) { counter++; outfile.println(counter + ":" + infile.nextLine()); } } catch (FileNotFoundException e) { System.err.println("cannot open file"); } catch (IOException e) { System.err.println("Error in reading: "+ e.getMessage()); } finally { if (infile != null) infile.close(); if (outfile != null) outfile.close(); } } }