Write down a java program segment to do the following: -Open file file1 for read
ID: 3821662 • Letter: W
Question
Write down a java program segment to do the following: -Open file file1 for reading which, as an example, has the following contents (an integer followed by different file names): 3 f1 f2 f3 f4 f5 f6 -Read the first integer from file1, and store its value in variable n. -Open the n^th file (for example, it would be f3 per contents of file1 in the above example) for writing. -Write "Bye" in the opened file and properly flush and close it. import java.util.*; import java.io.*; public class prog{public static void main(String []args){}}Explanation / Answer
Hi, Please find my implementation.
please let me know in case of any issue.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class prog {
public static void main(String[] args) throws FileNotFoundException {
// Opening file1
Scanner sc = new Scanner(new File("file1"));
// reading integer
int n = sc.nextInt();
// reading nth file name
String file = args[n];
// now file has name of nth file name
//opening file
PrintWriter pw = new PrintWriter(new File(file));
// writing "Bye" in file
pw.println("Bye");
pw.flush();
pw.close();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.