将 FileOutputStream 重定向到控制台 - Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16622106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirecting FileOutputStream to console - Java
提问by Pete855217
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):
我已经尝试创建以下测试方法来演示我想要实现的目标,方法是定义一个抽象的 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);
}
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?
Java 中有没有一种方法可以在运行时定义输出方法(文件或控制台),因此我可以在运行时使用相同的方法来执行其中任一操作?我想一个简单的方法是将 FileOutputStream 重定向到控制台 - 这可能吗?
回答by MadProgrammer
Basically, you need to create a method that simply takes a OutputStream
and writes all the details to it...
基本上,您需要创建一个方法,该方法只需要 aOutputStream
并将所有详细信息写入其中...
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 ;)
回答by bowmore
java.io.OutputStream
is already an abstraction of 'something you can write bytes to'. If your class interacts with an OutputStream and the clients of your class can choose what that OutputStream actually is (a file, the console, a null device, ...) then your class won't need to care about the type of OutpuStream is actually needed for a given context.
java.io.OutputStream
已经是“可以写入字节的东西”的抽象。如果您的类与 OutputStream 交互,并且您的类的客户端可以选择 OutputStream 的实际内容(文件、控制台、空设备等),那么您的类将不需要关心 OutpuStream 的类型是给定上下文实际需要。
So instead of your class trying to do what it needs to do andcreate OutputStreams for its clients, let it just focus on its true responsibility and let clients provide the OutputStream they desire.
因此,与其让您的类尝试做它需要做的事情并为其客户创建 OutputStreams,不如让它专注于其真正的责任,并让客户提供他们想要的 OutputStream。
So keep only one constructor :
所以只保留一个构造函数:
/**
* Constructs a new instance that will print to the given OutputStream
*/
PrintFlightSchedule(OutputStream stream);
回答by twahlfeld
You can create a FileOutputStream with a FileDescriptor instead of a string.
您可以使用 FileDescriptor 而不是字符串创建 FileOutputStream。
public FileOutputStream(FileDescriptor fdObj)
Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.
First, if there is a security manager, its checkWrite method is called with the file descriptor fdObj argument as its argument.
If fdObj is null then a NullPointerException is thrown.
This constructor does not throw an exception if fdObj is invalid. However, if the methods are invoked on the resulting stream to attempt I/O on the stream, an IOException is thrown.
公共文件输出流(文件描述符 fdObj)
创建文件输出流以写入指定的文件描述符,该文件描述符表示与文件系统中实际文件的现有连接。
首先,如果有一个安全管理器,它的 checkWrite 方法被调用,文件描述符 fdObj 参数作为它的参数。
如果 fdObj 为 null,则抛出 NullPointerException。
如果 fdObj 无效,此构造函数不会抛出异常。但是,如果在结果流上调用这些方法以尝试对流进行 I/O,则会引发 IOException。
And default FileDescriptors are:
默认的 FileDescriptor 是:
static FileDescriptor err
A handle to the standard error stream.
static FileDescriptor in
A handle to the standard input stream.
static FileDescriptor out
A handle to the standard output stream.
So the equivalent should be:
所以等价的应该是:
public static void testOutputStream(String fileNm, String msg) {
FileOutputStream os;
if (fileNm.equals("") ) { // No file name provided, write to console
os = new FileOutputStream(FileDescriptor.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);
}
回答by flup
Don't provide a filename String as a parameter, but a Writer. Your method's signature becomes
不要提供文件名字符串作为参数,而是提供 Writer。你的方法的签名变成
void PrintFlightSchedule(Writer writer);
The code you show would be the bit that creates the Writer on startup depending on runtime parameters:
您显示的代码将是根据运行时参数在启动时创建 Writer 的位:
public static Writer createOutputWriter(String fileNm) {
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());
}
}
return new BufferedWriter(new OutputStreamWriter(os));
}
Don't forget to flush the writer after output. How to write to Standard Output using BufferedWriter
不要忘记在输出后刷新编写器。 如何使用 BufferedWriter 写入标准输出