The write() method in the Java PrintStream class is

Asked 2 years ago, Updated 2 years ago, 22 views

When is the write()method used in the Java PrintStream class? I was looking at the Oracle explanation, but I didn't get it If there is an example, I want to see it once.

java

2022-09-21 22:14

1 Answers

The most popular stream object is the object in the PrintStream class.

System.out is an object in PrintStream, so if you output it to stdout (standard output), you can definitely use that object.

The PrintStream class has two methods defined for output: print and write.

Typically, print(ln) methods are used to write characters (columns), and write methods are used to write binary data.

-> System.out.println("aaaa")
aaaa

-> System.out.write(97)
a

-> byte[] b = "abcdef".getBytes()
|  |  Added variable b of type byte[] with initial value byte[6] { 97, 98, 99, 100, 101, 102 }

-> System.out.write(b)
abcdef

Because the System.out object is a PrintStream that stdouts to the screen, the above results are printed directly to the screen.

Example of outputting to a file

-> import java.io.*

-> File file = new File("out.txt")
|  |  Added variable file of type File with initial value out.txt

-> FileOutputStream fos = new FileOutputStream(
FileOutputStream(

-> FileOutputStream fos = new FileOutputStream(file)
|  |  Added variable fos of type FileOutputStream with initial value java.io.FileOutputStream@29ee9faa

-> PrintStream out = new PrintStream(fos)
|  |  Added variable out of type PrintStream with initial value java.io.PrintStream@cc285f4

-> out.print('a')

-> out.println("test")

-> byte[] b = "abcdef".getBytes()

-> out.write(b)

-> out.close()

The results of the out.txt file are as follows.

allinux@DESKTOP-6C4D789:~$ cat out.txt
atest
abcdef


2022-09-21 22:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.