Task #6: String, Methods and File I/O
In this task, you are being asked to write void methods that manipulate String, and write and read
to and from the text file in Java.
Write a method called replaceSpacesWithDots() that accepts one String argument, and
return the String after replacing all spaces in the String with dots.
You may use the following header for this method:
static String replaceSpacesWithDots(String sentence)
For example, if you read “The quick brown fox jumps over the lazy dog” from
the file, then the method should write
“The.quick.brown.fox.jumps.over.the.lazy.dog” to the output file.
NOTE: Read the input from the input-6-3.txt file.
Write the output to the output-6-3.txt file.
1. Create a program called FileIOStringReplaceLab3.java
2. Correctly write the output with appropriate messages.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class FileIOStringReplaceLab3 {
static String replaceSpacesWithDots(String sentence) {
return sentence.replaceAll(" ", ".");
}
public static void main(String[] args) {
String sentence = "";
try {
Scanner input = new Scanner(System.in);
File file = new File("input-6-3.txt");
input = new Scanner(file);
while (input.hasNextLine()) {
sentence = input.nextLine();
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
String newSentence = replaceSpacesWithDots(sentence);
try {
FileWriter fWriter = new FileWriter("output-6-3.txt");
fWriter.write("" + newSentence);
fWriter.close();
}
// Catch block to handle if exception occurs
catch (IOException e) {
// Print the exception
System.out.print(e.getMessage());
}
}
}
Comments
Leave a comment