Java PrintStream的意义和使用方法在哪里? [英] Java PrintStream significance and where to use this?

查看:205
本文介绍了Java PrintStream的意义和使用方法在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现许多程序员在他们的代码中使用PrintStream。我找了这个,但未能清楚地了解它的意义,为什么要使用它?



与其他输出流不同,PrintStream永远不会抛出IOException,数据会自动刷新到文件,即在写入字节数组后自动调用flush方法。



那么如果自动调用flush会有什么好处?



private PrintStream x = null;



现在,如果有人宣布像这样的x,可能是什么原因?

I found many programmers using PrintStream in their codes. I looked for this,but failed to get the clear idea of its significance,Why to use it?

"Unlike other output streams, a PrintStream never throws an IOException and the data is flushed to a file automatically i.e. the flush method is automatically invoked after a byte array is written."

So what's the benefit if flush is automatically invoked?

private PrintStream x = null;

Now what could be the possible reasons if someone declares x like this?

推荐答案

A PrintStream 只是位于 OutputStream 的顶部,它就是为了提供方便的写作方法(或者确实打印)到流。



其中 OutputStream 有一个非常低级的API( void write(byte [] b,int off,int len) PrintStream 包含允许您输出数据类型的方法可能对你的对象( void print(String s) void print(int i) )。这使得它更容易使用并且更自然,因为您不必在写入之前将数据转换为字节数组。



它还提供类似的东西自动刷新可以很方便,因为它不用担心。



私有PrintStream x = null;

这样声明的原因是流将在稍后初始化,很可能是在文件 OutputStream 可用。



希望这会有所帮助,

Fredrik
A PrintStream simply sits on top of an OutputStream and it's there to provide convenient methods for writing (or indeed printing) to the stream.

Where the OutputStream has a very low-level API (void write(byte[] b, int off, int len)) the PrintStream has methods that allow you to output data types you're likely to have on your objects (void print(String s) or void print(int i)). This makes it easier and to some more natural to use as you don't have to handle converting your data to a byte array before writes.

It also provides things like auto-flush which can be convenient as it's one thing less to worry about.

private PrintStream x = null;
The reason that's declared like that is that the stream is going to be initialized later, most likely when the File or OutputStream is available.

Hope this helps,
Fredrik


这篇关于Java PrintStream的意义和使用方法在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆