Write a program on the Linux system using the putty utility. The program should
ID: 3574691 • Letter: W
Question
Write a program on the Linux system using the putty utility. The program should get the name of the data file as a command line input. The program should check to find out of the data file already exists in the directory. If it does, the program should tell the user that the program will replace the existing file. It will prompt the user to enter “r” to replace the file or “q” to quit the program. If the user enters “r” (or if there is no file to replace) then the program will read numbers from the keyboard until the user enters control-d as the end of file marker. Each number will be stored on the disk file. write in Java netbeans
Explanation / Answer
/**
* Java program that prompts user to enter file
* name and check if file exist in current directory and
* then prompts to replace the file and prompt
* to enter numbers until cntl+d is entered.
* The the integer values are write to file.
*
* */
//WriteFileDemo.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class WriteFileDemo
{
public static void main(String[] args)
{
//Create a scanner object
Scanner scanner=new Scanner(System.in);
String fileName;
//read file name
System.out.println("Enter file name : ");
fileName=scanner.nextLine();
//Get current directory
String currentDirectory = System.getProperty("user.dir") ;
//add file name to directory
File file = new File(currentDirectory+"/"+fileName);
//check if file exists
boolean exists = file.exists();
if(exists)
{
System.out.println("The file "+fileName+" already exists.");
System.out.println("Do you want to replace it? [yor n]");
String choice=scanner.nextLine();
//reaplace if file exists
if(choice.equals("y") ||choice.equals("Y"))
{
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, false);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//create a buffer reader to read input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
try
{
int c = in.read();
//check end of reading
if (c != -1)
fos.write(c);
else
break;
}
catch (IOException e) {
System.err.println ("Error reading input");
}
}
}
else if(choice.equals("q"))
System.exit(0);
}
}
}
--------------------------
Sample output:
Enter file name :
data.txt
The file data.txt already exists.
Do you want to replace it? [yor n]
y
1
2
3
4
data.txt
1
2
3
4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.