O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reading and Writing Binary Data

Problem

Having connected, you wish to transfer binary data.

Solution

Construct a DataInputStream or DataOutputStream from the socket’s getInputStream( ) or getOutputStream( ).

Discussion

The simplest paradigm is:

DataInputStream is = new DataInputStream(sock.getInputStream(  ));
DataOutputStream is = new DataOutputStream(sock.getOutputStream(  ));

If the volume of data might be large, insert a buffered stream for efficiency. The paradigm is:

DataInputStream is = new DataInputStream(
    new BufferedInputStream(sock.getInputStream(  )));
DataOutputStream is = new DataOutputStream(
    new BufferedOutputStream(sock.getOutputStream(  )));

This program uses another standard service that gives out the time, this time as a binary integer representing the number of seconds since 1900. Since the Java Date class base is 1970, we convert the time base by subtracting the difference between 1970 and 1900. When I used this exercise in a course, most of the students wanted to add this time difference, reasoning that 1970 is later. But if you think clearly, you’ll see that there are fewer seconds between 1999 and 1970 than there are between 1999 and 1900, so subtraction gives the correct number of seconds. And since the Date constructor needs milliseconds, we multiply the number of seconds by 1,000.

The time base difference is the number of years multiplied by 365.25, multiplied by the number of seconds in a day. The earth’s mean orbital period is approximately 365.23 days, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required