2nd picture is of class File methods to be used in program 10. Write a program t
ID: 3920777 • Letter: 2
Question
2nd picture is of class File methods to be used in program 10. Write a program that will make a copy of a text file, line by line. Read the name of the existing file and the name of the new file-the copy-from the keyboard. Use the methods of the class File to test whether the original file exists and can be read. If not, display an error message and abort the program. Similarly, see whether the name of the new file already exists. If so, display a warning message and allow the user to either abort the program, overwrite the existing file, or enter a new name for the file.Explanation / Answer
CopyFileContent.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CopyFileContent {
public static void main(String[] args) throws FileNotFoundException {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the input file name: ");
String inputFileName = scnr.next();
System.out.println("Enter the output file name: ");
String outputFileName = scnr.next();
File input = new File(inputFileName);
if(input.exists() && input.canRead()) {
File output = new File(outputFileName);
int choice=-11;
while(output.exists()&& choice !=3&& choice !=1) {
System.out.println("Output file is already exist. Choose your option 1. Overwrite the file 2. Enter new file 3. Abort");
choice = scnr.nextInt();
if(choice == 2){
System.out.println("Enter the output file name: ");
outputFileName = scnr.next();
output = new File(outputFileName);
}
}
if(choice != 3) {
PrintWriter pw = new PrintWriter(output);
Scanner scan = new Scanner(input);
while(scan.hasNextLine()){
String line = scan.nextLine();
pw.write(line+" ");
}
pw.flush();
pw.close();
scan.close();
scnr.close();
System.out.println("File has been generated");
}
} else {
System.out.println("Input file does not exist");
}
}
}
Output:
Enter the input file name:
D:\data.txt
Enter the output file name:
D:\input.txt
Output file is already exist. Choose your option
1. Overwrite the file
2. Enter new file
3.Abort
2
Enter the output file name:
D:\input1.txt
Output file is already exist. Choose your option
1. Overwrite the file
2. Enter new file
3.Abort
1
File has been generated
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.