Day 10: Java I/O

Day 10: Java I/O

ยท

2 min read

The Java I/O (Input/Output) system provides the capability to read data from an external source and write data to an external destination. The I/O classes in Java contain a stream-oriented and a file-oriented approach.

Streams

A stream represents an input source or an output destination. Streams in Java can be:

  • Byte streams - Used for input/output of 8-bit bytes.

  • Character streams - Used for input/output of 16-bit Unicode characters.

The Stream classes in Java are:

// Byte streams
InputStream  
OutputStream

// Character streams   
Reader
Writer

There are various subclasses of these stream classes:

// Byte streams  
FileInputStream  
FileOutputStream
...

// Character streams      
FileReader   
FileWriter
...

To read from a stream:

InputStream in = new FileInputStream("file.txt");
int data = in.read(); // Reads a byte
while(data != -1) { // -1 indicates end of stream 
    // Process data 
    data = in.read();
}
in.close();

To write to a stream:

OutputStream out = new FileOutputStream("file.txt");
out.write(65); // Writes character 'A' 
out.write("Hello".getBytes());
out.close();

Files

The Files class provides utility methods to work with files and directories:

// Check if file exists
Files.exists(file);

// Delete file     
Files.delete(file);

// Create file    
Files.createFile(file);

// Copy file
Files.copy(source, target);

// Move file
Files.move(source, target);

Character Streams - Reader/Writer

The Reader and Writer classes are used for the input/output of characters instead of bytes. For example, to read from a file:

FileReader fin = new FileReader("file.txt");
int data;
while ((data = fin.read()) != -1) {
   // Process data
}
fin.close();

To write to a file:

FileWriter fout = new FileWriter("file.txt");
fout.write("Hello");
fout.close();

Serialization

Java provides the capability to persist objects to a stream and recreate them later. This is known as object serialization. To serialize an object:

// Write object to a file 
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.txt")); 
out.writeObject(object);
out.close();

To deserialize an object:

// Read object from file
ObjectInputStream in = new ObjectInputStream(new FileInputStream("file.txt"));
Object object =  in.readObject();       
in.close();

The class whose objects need to be serialized must implement the Serializable interface.

In summary, the Java I/O framework provides a simple yet powerful API to perform input and output operations on data stored in files, streams, and serial objects.

Did you find this article valuable?

Support Lexy Thinks by becoming a sponsor. Any amount is appreciated!

ย