/* * Important! You must import the util and io libraries for this to work! */ import java.util.Random; import java.util.StringTokenizer; import java.io.*; /* * This example program illustrates how to use a BufferedReader to read * line-by-line from an input file, how to use a StringTokenizer to * read words from a string, and how to use a FileWriter to write * strings to an output file. It also illustrates the use of exception * handling by try-catch to handle the potential I/O errors. */ public class TextCopy { public static void main(String[] args) { if(args[0] == null || args[1] == null) { System.out.println("usage: TextCopy "); System.exit(0); } try // We need try-catch because of potential problems with the files. { /* * We create a BufferedReader from the filename which is the first * first command-line argument. */ BufferedReader inputReader = new BufferedReader(new FileReader(args[0])); /* * We create a PrintWriter from the filename which is the second * command-line argument. */ PrintWriter outputWriter = new PrintWriter(new FileWriter(args[1])); /* The following while loop reads from the file line-by-line. */ boolean moreInput = true; String oneLine; while (moreInput) { oneLine = inputReader.readLine(); // Read a line from the file. if (oneLine == null) { moreInput = false; } else { StringTokenizer wordGetter = new StringTokenizer(oneLine); /* * The following while loop reads individual words from a string * and copies them word-by-word to the output file. */ while (wordGetter.hasMoreTokens()) { String aWord = wordGetter.nextToken(" \t\n\",.;:?"); System.out.println(aWord); // outputWriter.print(aWord); // outputWriter.print(" "); } outputWriter.println(); } } /* Now we close the input and output files. */ inputReader.close(); outputWriter.close(); } catch(IOException anError) { anError.printStackTrace(); // Show the function call stack for debugging. } } }