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

java program Filename(s): ReformatCode.java Public class: ReformatCode Package-v

ID: 3935263 • Letter: J

Question

java program

Filename(s): ReformatCode.java
Public class: ReformatCode
Package-visible class(es): none

Write a program that reformats Java source code from the next-line brace style to the end-of-line brace style. The program is invoked from the command line with the input Java source code file as args[0] and the name of the file to save the formatted code in as args[1]. The original file is left untouched. The program makes no other changes the source code, including whitespace.

For example, the following command converts the Java source code file Test.java to the end-of-line brace style.

}
The above source code would be reformatted into the following code, which is then saved in Test2.java:

}

Explanation / Answer

Hi,

Here is the program you have asked please check and comment below if any doubts are there

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

public class HelloWriter {

public static void main(String[] args) {

File filename = new File(args[0]);
if (!filename.exists()) {
System.out.println(filename + " does not exist.");
System.exit(1);
}
File filename2 = new File(args[1]);
if (!filename2.exists()) {
System.out.println(filename2 + " does not exist.");
System.exit(2);
}

StringBuilder buffer = new StringBuilder();
try {
Scanner input = new Scanner(filename);
while (input.hasNext()) {
String s = input.nextLine();

if (s.contains("{")) {
buffer.append(" {");
} else {
buffer.append(" " + s );
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

try {
PrintWriter output = new PrintWriter(filename2);
output.write(buffer.toString());
output.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}