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

In Collapse.java, write a method called collapseSpaces that accepts two paramete

ID: 3736798 • Letter: I

Question

In Collapse.java, write a method called collapseSpaces that accepts two parameters: (1) an input file Scanner and (2) an output file PrintStream. The method should read the contents of the file and output it with all its tokens separated by single spaces, collapsing any sequences of multiple spaces into single spaces. For example, consider the following text:

If this text were a line in the file, the same line should be output as follows:

Your main method should prompt the user for input and output filenames, then pass the appropriate Scanner and PrintStream to collapseSpaces method. If the output file already exists, print a message and end program without calling the collapseSpaces method.

Hints:

Your input and output files should be different files (filenames) to avoid overwriting files

Your method should work with input files that have multiple lines. Use a line-based approach. Keep the line breaks the same.

Explanation / Answer

import java.io.*;
import java.util.*;

public class Demo133{

   public static void collapseSpaces(Scanner sc, PrintStream ps){

         try {
              while (sc.hasNextLine()){
                 String line = sc.nextLine();
                 //System.out.println(line);
                 String[] a = line.split(" ");
                 for (int i = 0; i<a.length; i++){
                     String str = a[i] + " ";
                     ps.write(str.getBytes());
                 }
                 ps.write(" ".getBytes());
                
              }
              ps.flush();
              ps.close();
         }
         catch (Exception e){
             e.printStackTrace();
         }
   }
   public static void main(String[] args){
      try {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter input filename:");
         String in = sc.nextLine();
         System.out.println("Enter output filename:");
         String out = sc.nextLine();
         File input = new File(in);
         File output = new File(out);
         if (!input.exists()){
            System.out.println("Input file does not exist ");
            return;
         }
         if (output.exists()){
            System.out.println("Output file exists ");
            return;
         }
         Scanner fc = new Scanner(new FileInputStream(in));
         PrintStream ps = new PrintStream(new FileOutputStream(out));
         collapseSpaces(fc,ps);
      }
      catch (Exception e){
          e.printStackTrace();
      }

   }
}