Whymarrh
Whymarrh

Reputation: 13585

Transferring data in Java using streams

I have been reading the Java Tutorials on I/O in an attempt to understand stream and their proper usage. Say I have two devices that are connected, and an InputStream and OutputStream on both devices. How do I transfer data between the two?

For example, if I wanted to one device to send a bunch of words to the other device, which would then print them to the screen. How would that work?

public class Device1 {
    // assuming connectedDevice is something
    String[] words = new String()[]{"foo", "bar", "baz"};
    OutputStream os = connectedDevice.getOutputStream();
    InputStream is = connectedDevice.getInputStream();
    /*
        How to write to output stream?
    */
}

public class Device2 {
    // assuming connectedDevice is something
    ArrayList<String> words = new ArrayList<String>();
    OutputStream os = connectedDevice.getOutputStream();
    InputStream is = connectedDevice.getInputStream();
    /*
        How can I somehow get the words using `read()` and `put()`
        them into the ArrayList for use?
    */
}

Maybe I'm doing all of this wrong. Thanks in advance for any help in understanding.

Upvotes: 0

Views: 1537

Answers (2)

Keith Randall
Keith Randall

Reputation: 23265

If you just want to send characters, wrap your streams using an OutputStreamWriter on the writing side and an InputStreamReader on the reading side. You can write whole strings, then read one character at a time and print it. If you need to be really careful you should pick a fixed character encoding for both.

If you want to send whole simple objects like Strings, you can use DataOutputStream/DataInputStream. (For strings, use the UTF methods.)

If you want to get more complicated, you'll need to do serialization/deserialization of objects using ObjectOutputStream and ObjectInputStream.

Upvotes: 1

erickson
erickson

Reputation: 269877

It depends on how the devices are connected. For example, they might connect via TCP, or via a shared file system.

If you want to focus on streams, create an application that uses the file system. Then, use FileOutputStream and FileInputStream to understand the stream APIs.

If your focus is on networking, you'll want to study the networking tutorial too.

Upvotes: 2

Related Questions