How InputStream and OutputStream work in Java
In Java, I / O streams InputStream
and OutputStream
represent the concept of working with the outside world, whether it is a file on disk, a monitor screen, a network connection, or a printer. That is, everything that goes beyond the application.
If I understand correctly, then in the computer everything is ultimately a stream of bytes, and the Streams unify the work on this all. Just for each peripheral device, I write my own implementation of read()
and write()
.
Yes specific classes - for example, FileOutputStream
, which works specifically with files on disk. In it, the write()
method uses the native method, which performs the work of writing data to a file.
But, for example, I want to work with a file via ftp. Or I want to print the file via the printer. With this concept, I have to do it all through the same OutputStream
. How should I write an implementation of the OutputStream
class, specifically the write()
method, to send a stream of bytes to the printer? Or to another file via ftp connection?
1 answers
OutputStream
, like InputStream
, they are abstract classes, that is, they do not contain an implementation of one or more methods.
Specifically, the OutputStream
class does not have an implementation of the method:
public abstract void write(int oneByte) throws IOException;
However, the documentation says
All output stream subclasses should override both
write(int)
andwrite(byte[],int,int)
,write(byte[],int,int)
. The three argument overload is necessary for bulk access to the data. This is much more efficient than byte-by-byte access.
That is, it is necessary to implement the recording of a single byte and an array of bytes.
So you need to inherit the abstract class OutputStream
and implement the byte transfer to the device in the methods write
. This does not have to be a native
method, your class can contain a high-level definition of the interface for interacting with the device, for example, through libraries that implement connection to the device and organize transmission byte.
Example of writing in bytes directly to the printer (on the port "/dev/usb/lp0") in the language Java
:
BufferedWriter writer = new BufferedWriter(new FileWriter("/dev/usb/lp0"));
writer.write(new String("Hello world").getBytes());
writer.close();
However, I am not sure that Java will have enough rights, so I give the equivalent to C
:
int main()
{
FILE *printer = fopen("/dev/usb/lp0", "w");
fprintf(printer, "Hello World.\n\f");
fflush(printer);
fclose(printer);
return 0;
}