Java IO: Networking

Jakob Jenkov
Last update: 2023-01-22

The details of networking in Java is somewhat out of the scope of this Java IO tutorial. Java Networking is described in more detail in my Java Networking Tutorial. But, since network connections are a common source or destination of data, and because you use the Java IO API to communicate over a network connection, this text will briefly touch upon Java networking.

Once a network connection is established between two processes they communicate via the network connection just like they would with a file: Using an InputStream to read data, and an OutputStream to write data. In other words, while the Java Networking API is being used to establish a network connection between processes, Java IO is being used to exchange data between the processes once the connection is established.

Basically this means that if you have code that is capable of writing something to a file, that same something could easily be written to a network connection. All that is required is that your component doing the writing depends on an OutputStream instead of a FileOutputStream. Since FileOutputStream is a subclass of OutputStream this should be no problem.

The same is true for reading from a file, actually. A component capable of reading some data from a file, can easily read that same data from a network connection. Just make sure you reading component depends on an InputStream for reading it's data, and not a FileInputStream.

Here is an example:

public class MyClass {

    public static void main(String[] args) {

        InputStream inputStream = new FileInputStream("c:\\myfile.txt");

    public static void process(InputStream input) throws IOException {
        //do something with the InputStream

In this example the process() method cannot see if the InputStream it gets as parameter comes from the file system or the network (the example only shows the file system version). The process() method just works on an InputStream.

Jakob Jenkov

Featured Videos

Java ForkJoinPool

P2P Networks Introduction


Java Persistence
Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Next tutorial in this tutorial trail