Scanner s = new Scanner(new BufferedReader(new FileReader(inFile))); PrintWriter out = new PrintWriter(new FileWriter(outFile));We created a program
Silly that, ultimately,
read in a text file and printed the strings in that file, one
per line, to another file.
import java.util.*;
import java.io.*;
public class Silly
{
public static void main(String[] args)
{
String inFile = args[0], outFile = args[1];
// Get scanner connected to file
Scanner s = null;
try
{
s = new Scanner(new BufferedReader(new FileReader(inFile)));
}
catch(FileNotFoundException fe)
{
System.out.println("File " + inFile + " not found!");
return;
}
// Get an output writer connected to file
PrintWriter out = null;
try
{
out = new PrintWriter(new FileWriter(outFile));
}
catch(IOException ioe)
{
System.out.println("File " + outFile + " could not be created!");
return;
}
// Process file
while(s.hasNext())
{
String str = s.next();
out.println(str);
}
out.flush();
out.close();
}
}
PrintStream instead of
PrintWriter, since System.out is
a PrintStream. Notice how I misuse exceptions to
deal with missing command-line arguments. I should've just
checked args!
import java.util.*;
import java.io.*;
public class SillyMod
{
public static void main(String[] args)
{
// Get file names from args, or print usage message
// Here we use exceptions instead of checking args.length.
// This is an example of a bad use of exceptions!!!!!
String inFile = "", outFile = "";
try {
inFile = args[0];
outFile = args[1];
}
catch(Exception e) { // catches ArrayIndexOutOfBoundsException's
if (inFile.equals(""))
{
System.out.println("usage: java Silly <inFile> [<outFile>]");
return;
}
}
// Get our scanner working
Scanner s = null;
try
{
s = new Scanner(new BufferedReader(new FileReader(inFile)));
}
catch(FileNotFoundException fe)
{
System.out.println("File doesn't exist ... silly!");
return;
}
// Get our output writer (screen if file can't be created)
PrintStream out;
try {
out = new PrintStream(new FileOutputStream(outFile));
}
catch(IOException ioe)
{
out = System.out;
}
// Process
while(s.hasNext())
{
String str = s.next();
out.println(str);
}
out.flush();
out.close();
}
}