Java IO – 2 [ Examples ]

In this guide, we will explore some Java IO examples which consist of file, object and network.

What You Need

  • About 4 minutes
  • A favorite text editor or IDE
  • Java 8 or later

1. File

1.1 List All Files In A Directory

import java.io.File;

public class ListAllFilesOfDirectory {
    public static void main(String[] args) {
        String directory = "/home/ovo/github/BlogTests/java.io";

        File dir = new File(directory);

        listAllFiles(dir);
    }

    private static void listAllFiles(File currentFile) {
        if (currentFile == null || !currentFile.exists()) {
            return;
        }
        if (currentFile.isFile()) {
            System.out.println("\t" + currentFile.getName());
            return;
        }
        if (currentFile.isDirectory()) {
            System.out.println();
            System.out.println(currentFile.getName());
        }
        for (File file : currentFile.listFiles()) {
            listAllFiles(file);
        }
    }
}

The output of above code snippet is below :

java.io
        DatagramUDP.java
        CharArrayReaderTest.java
        FileWriterTest.java
        ListAllFilesOfDirectory.java
        PipedReaderWriterTest.java
        StringReaderTest.java
        ReadFromURL.java
        BufferedInputStreamTest.java
        CopyFile.java
        ReadFileLineByLine.java
        FileInputStreamTest.java
        ObjectInputOutputStreamTest.java
        FileReaderTest.java
        PipedInputOutputStreamTest.java
        ByteArrayOutputStreamTest.java
        PrintWriterTest.java
        FileOutputStreamTest.java
        PrintStreamTest.java
        DataInputOutputStreamTest.java
        ByteArrayInputStreamTest.java
        BufferedWriterTest.java
        BufferedReaderTest.java
        BufferedOutputStreamTest.java
        ObjectSerializationAndDeserialization.java
        StringWriterTest.java
        Sockets.java
        OutputStreamWriterTest.java
        CharArrayWriterTest.java
        InputStreamReaderTest.java

1.2 Copy File

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        String source = "/home/ovo/github/BlogTests/greeting";
        String target = "/home/ovo/github/BlogTests/greeting2";
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target))) {
            byte[] buffer = new byte[1024];

            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        }
    }
}

After running above code snippet, when checking the contents of greeting file and greeting2 file, we can see that they are the same :

cat greeting
hello world

cat greeting2
hello world

1.3 Read File Line By Line

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileLineByLine {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        String path = "/home/ovo/github/BlogTests/README.md";
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

Below is the output of above code snippet :

# BlogTests

This repo contains all the tests in my blog.

2. Object

Serialization And Deserialization

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectSerializationAndDeserialization {
    public static void main(String[] args)
            throws FileNotFoundException, IOException, ClassNotFoundException {
        String path = "/home/ovo/github/BlogTests/tom.bin";
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) {
            oos.writeObject(new Person("tom", 18));
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))) {
            Person p = (Person) ois.readObject();
            System.out.println(p);
        }
    }

    private static class Person implements Serializable {
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person [age=" + age + ", name=" + name + "]";
        }
    }
}

The output of above code snippet is below :

Person [age=18, name=tom]

3. Network

3.1 Sockets

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

public class Sockets {
    public static void main(String[] args) throws InterruptedException {
        final int port = 8081;

        Runnable server = () -> {
            try (ServerSocket ss = new ServerSocket(port)) {
                Socket accept = ss.accept();

                try (BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream()))) {
                    String line = reader.readLine();
                    System.out.println("server receives greeting message from client : " + line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        };

        new Thread(server).start();

        Runnable client = () -> {
            try (Socket s = new Socket("localhost", port)) {
                try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()))) {
                    writer.write("hello world");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        };

        int seconds = 5;
        System.out.println("wait " + seconds + " seconds before sending greeting message to server !");
        TimeUnit.SECONDS.sleep(seconds);

        new Thread(client).start();
    }
}

Below is the output of above code snippet :

wait 5 seconds before sending greeting message to server !
server receives greeting message from client : hello world

3.2 URL

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class ReadFromURL {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("https://www.google.fr/");

        System.out.println("protocol = " + url.getProtocol());
        System.out.println("host = " + url.getHost());
        System.out.println("path = " + url.getPath());
        System.out.println("port = " + url.getPort());
        System.out.println("file = " + url.getFile());

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(url.openStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (MalformedURLException e) {
            throw e;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The output of above code snippet is below :

protocol = https
host = www.google.fr
path = /
port = -1
file = /
...

3.3 Datagram

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.TimeUnit;

public class DatagramUDP {
    public static void main(String[] args) throws InterruptedException {
        final int port = 3000;
        final String host = "localhost";

        receive(port, host);

        TimeUnit.SECONDS.sleep(1);
        
        send(port, host);
    }

    private static void receive(final int port, final String host) {
        Runnable receiver = () -> {
            try (DatagramSocket ds = new DatagramSocket(port, InetAddress.getByName(host))) {
                byte[] buffer = new byte[1024];

                DatagramPacket dp = new DatagramPacket(buffer, buffer.length);

                ds.receive(dp);

                System.out.println("Data received : " + new String(dp.getData()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        };

        new Thread(receiver).start();
    }

    private static void send(final int port, final String host) {
        Runnable sender = () -> {
            try (DatagramSocket ds = new DatagramSocket()) {
                String greeting = "hello world";

                byte[] bytes = greeting.getBytes();
                int len = bytes.length;
                InetAddress address = InetAddress.getByName(host);

                ds.send(new DatagramPacket(bytes, len, address, port));

                System.out.println("Data (" + greeting + ") sent ...");
            } catch (IOException e) {
                e.printStackTrace();
            }
        };

        new Thread(sender).start();
    }
}

Below is the output of above code snippet :

Data received : hello world
Data (hello world) sent ...