JAVA - IO Streams and Files

Streams in Java

A stream is a sequence of data. 

In Java, a stream is composed of bytes. 

It's called a stream because it is a continuous flow of data.


1.      Java treats flow of data as stream.

2.      Java streams are classified into two basic types: input stream and output stream.

3.      The java.io package contains a large number of stream classes to support the streams.


This package provides system input and output through data streams, serialization and the file system.

1.      Java I/O (Input and Output) is used to process the input and produce the output.

2.      Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

3.      We can perform file handling in Java by java.io API.


IO Streams

Java Classes for IO Stream




JAVA Class Names




Java program to handle file(s):


import java.io.File;


public class FileExample {

    public static void main(String[] args) {

        // Represents a file named "my_document.txt" in the current directory

        File myFile = new File("my_document.txt");


        // Represents a file in a specific directory

        File anotherFile = new File("C:/Users/YourUser/Documents/data.csv");


        System.out.println("File exists: " + myFile.exists()); // Checks if the file exists

    }

}


Reading from a File:

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;


public class ReadFileExample {

    public static void main(String[] args) {

        try (BufferedReader reader = new BufferedReader(new FileReader("my_document.txt"))) {

            String line;

            while ((line = reader.readLine()) != null) {

                System.out.println(line);

            }

        } catch (IOException e) {

            System.err.println("Error reading the file: " + e.getMessage());

        }

    }

}


=>wrap the FileReader in a BufferedReader for better performance


Writing to a File:

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;


public class WriteFileExample {

    public static void main(String[] args) {

        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {

            writer.write("This is the first line.");

            writer.newLine(); // Adds a new line character

            writer.write("This is the second line.");

        } catch (IOException e) {

            System.err.println("Error writing to the file: " + e.getMessage());

        }

    }

}


Appending to a File:

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;


public class AppendFileExample {

    public static void main(String[] args) {

        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt", true))) {

            writer.newLine();

            writer.write("This line is appended.");

        } catch (IOException e) {

            System.err.println("Error appending to the file: " + e.getMessage());

        }

    }

}


Reading a Binary File:

import java.io.FileInputStream;

import java.io.IOException;


public class ReadBinaryFile {

    public static void main(String[] args) {

        try (FileInputStream fis = new FileInputStream("image.jpg")) {

            int byteRead;

            while ((byteRead = fis.read()) != -1) {

                // Process each byte (e.g., print its integer value)

                System.out.print(byteRead + " ");

            }

            System.out.println("\nFinished reading the binary file.");

        } catch (IOException e) {

            System.err.println("Error reading the binary file: " + e.getMessage());

        }

    }

}


Writing to a Binary File:

import java.io.FileOutputStream;

import java.io.IOException;


public class WriteBinaryFile {

    public static void main(String[] args) {

        byte[] dataToWrite = { 65, 66, 67, 10, 68, 69 }; // Example byte data (ASCII for ABC, newline, DE)


        try (FileOutputStream fos = new FileOutputStream("output.bin")) {

            fos.write(dataToWrite);

            System.out.println("Successfully wrote binary data to output.bin");

        } catch (IOException e) {

            System.err.println("Error writing to the binary file: " + e.getMessage());

        }

    }

}


Classes for Text Files: 

FileReader: Provides methods to read characters and arrays of characters from a file.

FileWriter: Provides methods to write characters, character arrays, and strings to a file.

BufferedReaderOffers methods like readLine() to read a line of text at a time, for text file processing.

BufferedWriterOffers methods like write() for characters and strings, and newLine() to write a platform-specific line separator.


Classes for Binary Files:

FileInputStream: Provides methods like read() to read bytes individually or into byte arrays.

FileOutputStream: Provides methods like write() to write individual bytes or byte arrays. You can also specify the append mode in its constructor.

BufferedInputStream: Wraps an InputStream and provides the same read() methods but with buffering.

BufferedOutputStream: Wraps an OutputStream and provides the same write() methods but with buffering.

















Comments

Popular Posts