Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Databases And Information Systems 1 International Baltic Conference Dbandis 2020 Tallinn Estonia June 19 2020 Proceedings

Authors: Tarmo Robal ,Hele-Mai Haav ,Jaan Penjam ,Raimundas Matulevicius

1st Edition

303057671X, 978-3030576714

Students also viewed these Databases questions