Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write down a java program segment to do the following: Open file file1 for readi

ID: 3816074 • 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 file 1, 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();

   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote