Sure, the same way as with the name of the input file with Scanner
The following program (a version of a previous example) prompts the user for both the names of the input file and the output file.
import java.util.Scanner;
import java.io.*;
class NamedFileInOut
{
public static void main (String[] args) throws IOException
{
int num, square;
// Scanner for user input
Scanner user = new Scanner( System.in );
String inputFileName, outputFileName;
// prepare the input file
System.out.print("Input File Name: ");
inputfileName = user.nextLine().trim();
File input = new File( fileName );
Scanner scan = new Scanner( input );
// prepare the output file
System.out.print("Output File Name: ");
outputfileName = user.nextLine().trim();
File output = new File( fileName );
PrintStream print = new PrintStream( output );
// processing loop
while( scan.hasNextInt() )
{
num = scan.nextInt();
square = num * num ;
print.println("The square of " + num + " is " + square);
}
// close the output file
print.close();
}
}
This program can be used as the basis for many others. Several of the programming exercises can be done by copying this program and making small changes to the processing loop.
How could you create a program that adds up all the integers in a file of text integers?