Java (N)IO

Jussi Pohjolainen

TAMK University of Applied Sciences » ICT

Intro

Streams

Reading and Writing Bytes

CopyBytes.java (from Java Tutorial)

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytes {
    public static void main(String[] args) throws IOException {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream("xanadu.txt");
            out = new FileOutputStream("outagain.txt");
            int c;

            while ((c = in.read()) != -1) {
                out.write(c);
            }

        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}         
         

Reading and Writing Characters

CopyCharacters.java (from Java Tutorial)

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyCharacters {
    public static void main(String[] args) throws IOException {
        FileReader inputStream = null;
        FileWriter outputStream = null;

        try {
            inputStream = new FileReader("xanadu.txt");
            outputStream = new FileWriter("characteroutput.txt");

            int c;
            while ((c = inputStream.read()) != -1) {
                outputStream.write(c);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}       
         

Buffered Streams

CopyLines.java (from Java Tutorial)

import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;

public class CopyLines {
    public static void main(String[] args) throws IOException {
        BufferedReader inputStream = null;
        PrintWriter outputStream = null;

        try {
            inputStream = 
                new BufferedReader(new FileReader("xanadu.txt"));
            outputStream = 
                new PrintWriter(new FileWriter("characteroutput.txt"));

            String l;
            while ((l = inputStream.readLine()) != null) {
                outputStream.println(l);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}    
         

Object Streams: Serialization

OpenAndSaveCar.java

import java.io.*;

class Car implements Serializable {
    private String brand;
    
    public Car(String brand) {
        setBrand(brand);
    }
    
    public String getBrand() {
        return brand;
    }
    
    public void setBrand(String brand) {
        this.brand = brand;
    }
}

class OpenAndSaveCar {
    public static void main(String [] args) {
        Car datsun = new Car("Datsun 100a");
        
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            // Save the object
            fos = new FileOutputStream("car.dat");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(datsun);
            
            // Read the object
            fis = new FileInputStream("car.dat");
            ois = new ObjectInputStream(fis);
            Car datsun2 = (Car) ois.readObject();
            
            System.out.println(datsun2.getBrand());
            
        } catch(IOException e) {
            e.printStackTrace();
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fos != null) {
                    fos.close();
                }
                if(oos != null) {
                    oos.close();
                }
                if(fis != null) {
                    oos.close();
                }
                if(ois != null) {
                    oos.close();
                }
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
}         
         

Object Streams: Serialization in detail

NIO: High performance IO

Streams and Blocks

Channels and Buffers

Buffer types

About channels

Example: Reading

FileInputStream fin = new FileInputStream( "data.txt" ); 
// Get a channel via the FileInputStream
FileChannel fc      = fin.getChannel(); 
// Create a buffer
ByteBuffer buffer   = ByteBuffer.allocate( 1024 );
// Read from channel into a buffer
fc.read( buffer ); 

Example: Writing

FileOutputStream fout = new FileOutputStream( "data.txt" ); 
// Get a channel via the FileOutputStream
FileChannel fc = fout.getChannel(); 
// Create a buffer
ByteBuffer buffer = ByteBuffer.allocate( 1024 ); 
// Data to be saved
byte [] message = "this will be saved".toByteArray();
// Write into buffer
for ( int i=0; i<message.length; i++ ) { 
    buffer.put( message[i] ); 
} 
// Flip the buffer, this will be explained later
buffer.flip();
// Writes SOME bytes from the buffer!
fc.write( buffer );

Buffer internals

Buffer Example 1

Buffer Example 2

Buffer Example 3

Buffer Example 4

Buffer Example 5

Buffer Example 6

The position cannot go past the limit!

Buffer Example 7

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class CopyFiles {
    public static void main(String args []) throws Exception {
	// Must be started given input and output files
	if (args.length<2) {
	    System.err.println("Usage: java CopyFile infile outfile");
	    System.exit(1);
	}
	
	String infile  = args[0];
	String outfile = args[1];
	
	// Get streams to the files
	FileInputStream fin   = new FileInputStream (infile);
	FileOutputStream fout = new FileOutputStream(outfile);
	
	// Get channels to the files
	FileChannel fcin  = fin.getChannel();
	FileChannel fcout = fout.getChannel();
      
	// Create byte buffer to be used in reading and writing
	ByteBuffer buffer = ByteBuffer.allocate(1024);
	
	// Let's start reading and writing
	while (true) {
	    // Set the position = 0
	    // Set limit to capacity (1024)
	    buffer.clear();
	    
	    // Read sequence of bytes from the infile into a buffer
	    int numberOfReadBytes = fcin.read(buffer);
	    
	    // If there is no bytes left in the infile, break
	    // out of the loop
	    if (numberOfReadBytes == -1) {
		break;
	    }
	    
	    // Limit is set to position
	    // and then the position is set to zero
	    buffer.flip();

	    // write all the bytes from the buffer to outfile
	    int numberOfWrittenBytes = 0;
	    do {
		numberOfWrittenBytes += fcout.write(buffer);
	    } 
	    while(numberOfWrittenBytes < numberOfReadBytes);
	}
    }
}