File Name from User Input

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

Sure, the same way as with the name of the input file with Scanner

File Name from User Input

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.

QUESTION 14:

How could you create a program that adds up all the integers in a file of text integers?