I have written a small program that reads input from a text file and then writes this output to a text file. The method contains a switch which decides whether to output to the file as text or as a literal string of the bytes. How could I refactor this code to only include a single if statement block instead of two to switch between these two modes? I am also interested if there is a more optimal way of writing this code overall.
I have tried to create just one switch at the beginning of the code which would change the output files from output-text-txt to output-bytes.txt (which are located in the resources folder) as well as changing the writing method (whether it writes the integer or string literals). I encounter difficulty when I need to write the bytes because the method asks for either an integer or a string and I am not sure how I would change these writing methods with just one if statement at the beginning of the code (due to it asking for int c as a parameter)
public class ByteStreamTest {
private static File input;
private static File output;
public static void main(String args[]) throws Exception {
new ByteStreamTest().write(true);
new ByteStreamTest().write(false);
}
public ByteStreamTest() {}
public void write(boolean asText) {
input = new File(getClass().getClassLoader().getResource("input.txt").getPath());
if (asText) {
output = new File(getClass().getClassLoader().getResource("output-text.txt").getPath());
} else {
output = new File(getClass().getClassLoader().getResource("output-bytes.txt").getPath());
}
FileInputStream in = null;
FileWriter fw = null;
try {
in = new FileInputStream(input);
fw = new FileWriter(output);
int c;
while ((c = in.read()) != -1) {
if (asText) {
fw.write(c);
} else {
fw.write(String.valueOf(c) + System.getProperty("line.separator"));
}
}
in.close();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This isn't really a question that has to do with the functionality of the code, I am simply interested in refactoring the code to include as little if statements as possibly optimizing it further.
write()
. Then write two implementations: MyTextWriter and MyBinaryWriter. Now you only need one if statement to decide which class to instantiate. \$\endgroup\$