将FileOutputStream重定向到控制台-Java

Pet*_*217 1 java console

我只想重写代码,以减少类中执行相同操作但可以写入文件或控制台的方法的数量,因此我可以执行以下操作:

PrintFlightSchedule(String aFileName); // prints to a file
PrintFlightSchedule(); // writes to console.
Run Code Online (Sandbox Code Playgroud)

我试图通过定义抽象OutputStream,然后将其实例化为PrintStream或控制台(通过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);
}
Run Code Online (Sandbox Code Playgroud)

坦率地说,这是半定的,但它可以使您了解我想要实现的目标。

Java中是否有一种在运行时定义输出方法(文件或控制台)的方法,因此我可以在运行时使用相同的方法来执行输出方法?我猜一个简单的方法是将FileOutputStream重定向到控制台-可能吗?

Mad*_*mer 5

基本上,您需要创建一个仅接受a OutputStream并将所有详细信息写入其中的方法...

然后创建一些辅助方法,只需使用适当的流即可调用它。

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);
}
Run Code Online (Sandbox Code Playgroud)

您可能还想看看Java语言代码约定 ...这将使人们更容易阅读和理解您的代码;)