import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner;
public class FileIO_Block { public static void main(String[] args) { // Create the file objects. File inFile = new File("C:/temp/infile.txt"); File outFile = new File("C:/temp/outfile.txt"); // Pass the file objects to a method for processing. copyFile(inFile, outFile); }
/** A very simplistic file copy example */
public static void copyFile(File inputFile, File outputFile) {
try { // The means to "TRY" the action, but it might possibly fail...
// The scanner will read from the the inFile.
Scanner scanner = new Scanner(inputFile);
// The writer will write to the out file.
PrintWriter output = new PrintWriter(outputFile);
// Read the data from the input file and and write it to the out file.
// NOTE: The "prepends" the word OUTPUT: to each line.
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
output.println("OUTPUT: " + line);
}
// Cleanup by closing the input and output objects.
scanner.close();
output.close();
} catch (FileNotFoundException ex) { // If the file was not found, produce a message.
System.err.println("The File could not be found: " + ex.getMessage());
}
}
}