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

2.1 Define a public static method named f2s that takes a single string argument

ID: 3831238 • Letter: 2

Question

2.1 Define a public static method named f2s that takes a single string argument the name of a file the method returns a conceivably very large! String that is an exact copy of the contents of the file if the file cannot be opened the method returns null

EXAMPLE QUESTIONS WITH ANSWERS:

Q. Given an initialized String variable outfile, write a statement that declares a PrintWriter reference variable name output and initializes it to a reference to a newly created PrintWriter object associated witha file whose name is given by outfile. (Do not concern yourslef with any possilbe exeptions here--assume they are handled elsewhere.)

A. PrintWriter output = new PrintWriter(outfile);

Q. Given an initialized String variable fileName, write a sequence of statements that create a file whose name is given by the variable and whose content is a single line consisting of "This Is FIle:" followed by the name of the file. Make sure that the data written to the file has been flushed from its buffer and that any system resources used during the course of running these statements have been released. (Do not concern yourself with any possible exceptions here--assume they are handled elsewhere)

A. FileWriter fw = new FileWriter(fileName); BufferedWriter bw = new BufferedWriter(fw); bw.write("This Is File: " + fileName); bw.close();

Explanation / Answer

FileContentTest.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class FileContentTest {

  
   public static void main(String[] args) throws FileNotFoundException {
       Scanner scan = new Scanner(System.in);
       System.out.println("Enter the file name: ");
       String filename = scan.next();
       System.out.println(f2s(filename));
   }
   public static String f2s(String filename) throws FileNotFoundException{
       File file = new File(filename);
       if(file.exists()){
           Scanner scan = new Scanner(file);
           String s = "";
           while(scan.hasNextLine()){
               s = s + scan.nextLine()+" ";;
           }
           return s;
       }
       else{
           return null;
       }
   }
}

Output:

Enter the file name:
D:\data.txt
0.5 3 10 70 90 80 20