Page 604 - Introduction to Programming with Java: A Problem Solving Approach
P. 604
570 Chapter 14 Exception Handling CreateNewFile Program
In Figure 14.11, the CreateNewFile program attempts to create an empty file with a user-specified name. We cover files in detail in the next chapter. Since this example views files only “from the outside,” at this point you don’t need to understand file details. So why did we decide to use a file example prior to the files chapter? Because we wanted a good checked exception example and file programs provide for that. It would make more sense to use previously covered material for our checked exception example, but that wasn’t re- ally an option. Our previously covered commands don’t throw checked exceptions.
The CreateNewFile program prompts the user for the name of a file that is to be created. If the file exists already, the program prints a “Sorry, file already exists.” message. If the file does not exist, it creates the file. In doing all that, the program uses the File class and its application programming interface (API). More
/*******************************************************
*
CreateNewFile.java
Dean & Dean
This creates a new file.
*******************************************************/
*
*
*
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
Apago PDF Enhancer
public class CreateNewFile
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String fileName; // user-specified file name
File file;
System.out.print("Enter file to be created: ");
fileName = stdIn.nextLine();
file = new File(fileName);
if (file.exists())
API constructor call
APImethodcall
{
}
else
System.out.println("Sorry, file already exists.");
}
// end CreateNewFile class
}
// end main
{
API method call
}
file.createNewFile();
System.out.println(fileName + " created.");
Figure 14.11 Draft of CreateNewFile program which is supposed to create a new file