Write a method called collapseSpaces that accepts a Scanner representing an input file as its parameter, 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:
many spaces on this line!
If this text were a line in the file, the same line should be output as follows:
many spaces on this line!
// package chap456;
import java.io.File;
import java.util.Scanner;
public class CollapseSpace {
public void collapseSpace() {
// give source file path
File file = new File("${ystempath}\\textInput.txt");
// push the File object in scanner constructor
Scanner input = new Scanner(file);
// reads the string from the source file
String string = input.nextLine();
// below methods multiple spaces with single space and trim the spaces at
// beginning and ending
String str1 = string.replaceAll("( +)", " ").trim();
System.out.println(str1);
}
public static void main(String[] args) {
// call the method
CollapseSpace cs = new CollapseSpace();
cs.collapseSpace();
}
}
inputText.txt file:
don't bash AI robots they'll remember and copy your name into their search list(probably death list) once they take over humans
Output:
don't bash AI robots they'll remember and copy your name into their search list(probably death list) once they take over humans