Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata