Question
Copying a File Write a program that prompts the user for a filename, then opens a Scanner to the file and copies it, a line
Copying a File
Write a program that prompts the user for a filename, then opens a Scanner to the file and copies it, a line at a time, to the standard output. If the user enters the name of a file that does not exist, ask for another name until you get one that refers to a valid file. Some things to consider:
* Remember that you can create a Scanner from a File object. Refer Chapter 5.5 for using scanner to read from a file.
* Creating a Scanner from a File object may throw a FileNotFoundException -- this is how you will know if the file does not exist. Add try-catch clause to handle such an exception. Make sure your program still loops and asks for a new filename if the current file does not exist.
* Remember that the scope of a variable declared inside a try is the try itself -- it does not extend to the following code. Furthermore, the compiler knows that an initialization that occurs inside a try may or may not get executed, as the try may be thrown out of first. So any variable that you want to use in and after the try must be declared and initialized outside of the try.
//**********************************************************
// CopyFile.java
//
// Copies a file to the standard output.
//**********************************************************
import java.util.Scanner;
import java.io.*;
public class CopyFile
{
public static void main(String[] args)
{
String filename = null;
Scanner fileScanner = null;
Scanner scan = new Scanner(System.in);
do{
try
{
System.out.print("Enter a filename: ");
filename = scan.next();
fileScanner = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("File " + filename + " does not exist, please try again.");
}
}
while(fileScanner == null);
while (fileScanner.hasNext())
{
System.out.println(fileScanner.nextLine());
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started