java Write a method called collapseSpaces that accepts a Sca

java

Write a method called collapseSpaces that accepts a Scanner representing an input file and a PrintStream representing an output file as its parameters, then reads that file and outputs 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:

You will want to place the method in a class to test it. Call the class CollapseSpaces

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.

Solution

CollapseSpaces.java

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


public class CollapseSpaces {

  
   public static void main(String[] args) throws FileNotFoundException {
       File inputFile = new File(\"D:\\\\input.txt\");
       File outputFile = new File(\"D:\\\\output.txt\");
       if(inputFile.exists()){
           Scanner scan = new Scanner(inputFile);
           PrintStream ps = new PrintStream(outputFile);
           collapseSpaces(scan,ps);
           System.out.println(\"Spaces have been removed\");
       }
       else{
           System.out.println(\"File does not exist\");
       }

   }
   public static void collapseSpaces(Scanner input, PrintStream ps){
       while(input.hasNextLine()){
           String words[] = input.nextLine().split(\"\\\\s+\");
           for(String word: words){
               ps.print(word);
               ps.print(\" \");
           }

     ps.println();

}
       ps.flush();
       ps.close();
   }

}

Output:

Spaces have been removed

Input.txt

many spaces on this line!

Output.txt

many spaces on this line!

java Write a method called collapseSpaces that accepts a Scanner representing an input file and a PrintStream representing an output file as its parameters, the
java Write a method called collapseSpaces that accepts a Scanner representing an input file and a PrintStream representing an output file as its parameters, the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site