简体   繁体   中英

printing Integer using BufferedOutputStream in java

Need to print a million values in console, System.out.println() is comparatively slow when compared to BufferedOutputStream ( from what I read ).

So I tried to print this way:

OutputStream out = new BufferedOutputStream (System.out);
out.write(sum);

Since sum is of the type int , and the out.write() is printing in bytes. I tried to convert bytes to decimal, which gave me a compilation error saying:

byte cannot be dereferenced

So, my problem is: to print integer values in decimal format using BufferedOutputStream .

Since, I did not find any solution here in printing int values using BufferedOutputStream , I am desperately looking for an answer.

The problem you have is that displaying text on the console is much slower than generating it. You can use a buffer and if redirected to a file, instead of the screen this will be faster, however if you are actually displaying on the screen it won't be much faster. What buffering can do is reduce the amount of scrolling since it writes to the screen in lumps of text instead of one line at a time.

Note: BufferedOutputStream writes binary not text. It will be faster but is not human readable. If you want human readable I suggest using PrintWriter which is designed to write text.

PrintWriter out = new PrintWriter(new BufferedWriter(
                                  new OutputStreamWriter(System.out, "UTF-8")));

// call many times
out.print(num);

// to flush the buffer so all the data can be read.
out.flush();

You could use a StringBuilder, however this is;

  • slower as you are not displaying text until the whole string has been created. As noted, the displaying of the text is your main problem.
  • uses as much memory as the output, and doesn't scale well.

Hope this will help...

byte[] ascii = Integer.toString(sum).getBytes();

OutputStream console = new BufferedOutputStream(System.out);

try {

  console.write(ascii);

  console.flush();

} catch (IOException e) {

  e.printStackTrace();

}

But you'll have to check if this code is faster than

System.out.println(sum);

使用 BigInteger(bytes),它会给你一个 BigInteger 格式的整数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM