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:

This will slow down disk IO.

File Name from User Input

The next example program writes to a disk file named by the user. The trim() method removes leading and trailing spaces from the user data. Two try{} blocks are used. The first catches errors in creating the file; the second catches errors in writing data to it.

import java.io.*;
import java.util.Scanner;

class CreateFile
{
  public static void main ( String[] args ) 
  {

    // Get filename and create the file
    FileWriter writer = null;
    Scanner scan = new Scanner( System.in );
    String fileName = "";
    System.out.print("Enter Filename-->");  
    
    try
    {
      fileName = scan.next();
      writer = new FileWriter( fileName );
    }
    catch  ( IOException iox )
    {
      System.out.println("Error in creating file");
      return;
    }
      
    // Write the file.
    try
    {  
      writer.write( "Behold her, single in the field,/n"  );  
      writer.write( "Yon solitary Highland Lass!/n"  );  
      writer.write( "Reaping and singing by herself;/n" );  
      writer.write( "Stop here, or gently pass!/n"  );  
      writer.close();
    }
    catch ( IOException iox )
    {
      System.out.println("Problem writing " + fileName );
    }
  }
}

QUESTION 12:

(Review: ) What is a buffer?