Write a program that reads a file from a standard input and rewrites the file to
ID: 3824786 • Letter: W
Question
Write a program that reads a file from a standard input and rewrites the file to standard output, replacing all tab characters ' ' with the appropriate number of spaces. Make the distance between tab columns a constant and set it to 3. Then expand tabs to the number of spaces necessary to move to the next tab column. That may be less than three spaces. For example, consider the line containing "| | |". The first tab is changed to three spaces, the second to two spaces, and the third to one space.Explanation / Answer
package code;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CheggProblem001
{
//path from where the file is to be read
private static final String FILENAME = "Desktop\test.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
//reading each line
while ((sCurrentLine = br.readLine()) != null) {
//rewriting to standard output -- (1)
System.out.println(sCurrentLine);
//checking for tab in the line that was read
if (sCurrentLine.contains(" "))
{
System.out.println("after replacing tab with space"); //this is not required, just to differentiate the edited lines
sCurrentLine = sCurrentLine.replaceAll(" ", " ");
System.out.println(sCurrentLine); // this can be moved outside the if statement and the (1) can be removed to have just one print statement
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.