I'd like to rewrite and simply my code to cut down on the number of methods in a class that do exactly the same thing but either write to a file, or to a console so I can do things like:
PrintFlightSchedule(String aFileName); // prints to a file
PrintFlightSchedule(); // writes to console.
I've tried creating the following test method just to demonstrate what I'my trying to achieve, by defining an abstract OutputStream, then instantiating it as either a PrintStream, or console (via System.out):
public static void testOutputStream(String fileNm, String msg) {
OutputStream os;
if (fileNm.equals("") ) { // No file name provided, write to console
os = System.out;
}
// File name provided, write to this file name
else {
try {
os = new FileOutputStream(fileNm);
}
catch (FileNotFoundException fe) {
System.out.println("File not found " + fe.toString());
}
}
// Use the output stream here - ideally println method?
// os.println or write(6);
}
This is admittedly half-assed, but it gives you an idea what I'd like to achieve.
Is there a way in Java to define the output method (file or console) at run-time, so I can use the same methods to do either, at runtime? I guess a simple way would be to redirect the FileOutputStream to the console - is that possible?
Basically, you need to create a method that simply takes a OutputStream and writes all the details to it...
Then you create some helper methods that simply call it with the appropriate stream...
public void printFlightSchedule(OutputStream os) throws IOException {
// Write...
}
public void printFlightSchedule(File file) throws IOException {
FileOutputStream fis = null;
try {
fis = new FileOutputStream(file);
printFlightSchedule(fis);
} finally {
try {
} catch (Exception e) {
}
}
}
public void printFlightSchedule() throws IOException {
printFlightSchedule(System.out);
}
You may also want to take look at the Code Conventions for the Java Language...It will make it easier for people to read and understand your code ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With