Skip to main content

Introduction to Java Programming

  What is Java? Java is a programming language and a platform. Java is a high-level, robust, object-oriented and secure programming language. Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java. Firstly, it was called  Greentalk  and the file extension was  .gt . After that, it was called  Oak . Initially Java was designed for small, embedded systems in electronic appliances like set-top boxes. Platform:  Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime environment (JRE) and API(Application Programming Interface), it is called a platform. The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High performance, Multithreaded, Architecture neutral, Object-oriented, Interpreted, and Dynamic". Currently, Java is used in internet programming, mobile devices, games, e-business so

28. File Handling in Java

 

File Handling

  • File handling is used to store a data permanently in computer.
  • Using file handling, we can store our data in Secondary memory (Hard Disk).
  • The File class of the package java.io allows us to handle and work with different formats of files.
  • For reading and writing operations, we have two basic types of stream
    1. Byte Stream
      1. FileOutputStream class (To write in file)
      2. FileInputStream class (To read from file)
    2. Character Stream
      1. FileWriter class (To write in file)
      2. FileReader class (To read from file)

Creating a File

  • To create a file in Java, we can use the createNewFile() method of File class.
  • This method returns a Boolean value: true if the file was successfully created and false if the file already exists.
  • The method is enclosed in a try-catch block as it throws an IOException if the file cannot be created for some reason.
  • However FileWriter and FileOutputStream also creates the output file, if it not present already.
import java.io.File;
import java.io.IOException;

class CreatingAFile {
    public static void main(String[] args) {
        File myFile = new File("MyTextFile.txt");
        try {
            myFile.createNewFile();
            System.out.println("File creation successfull... ");
        } catch (IOException io) {
            System.out.println("File not created...");
        }
    }
}

Writing in a File

  • FileWriter is useful to create a text file and writing characters into it.
  • BufferedWriter can be used along with FileWriter to improve speed of execution.
  • FileOutputStream is useful to create a text file and writing bytes into it.
  • FileOutputStream is a subclass of OutputStream.
  • BufferedOutputStream can be used along with FileOutputStream to improve speed of execution.
  • To write into the file from a buffer, we can use the flush() method.
Program 1:

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

class WritingInFile {
    public static void main(String[] args) {
        try {
            FileWriter myFWriter = new FileWriter("poem.txt");
            myFWriter.write("You gave light to my soul\nYou helped me to be whole\n
            I have felt love for you before\nAnd it will be more and more,\nYou are mine, my dear\n
            You are the angel from above\nWho taught me how to love.\nPlease, forever keep me near.\n");
            myFWriter.append("\n- A poem by Writer");
            myFWriter.close();
            System.out.println("Successfully written in the file...");
        } catch (IOException io) {
            System.out.println("An exception occurred...");
        }
    }
}

Program 2:

import java.io.*;

class WritingInFile {
    public static void main(String[] args) {
        try {
            FileWriter myFWriter = new FileWriter("poem.txt");
            BufferedWriter bWriter = new BufferedWriter(myFWriter);
            bWriter.write("You gave light to my soul\nYou helped me to be whole\n
            I have felt love for you before\nAnd it will be more and more,\nYou are mine, my dear\n
            You are the angel from above\nWho taught me how to love.\nPlease, forever keep me near.\n");
            bWriter.append("\n- A poem by Writer");
            bWriter.flush();
            bWriter.close();
            System.out.println("Successfully written in the file...");
        } catch (IOException io) {
            System.out.println("An exception occurred...");
        }
    }
}

Output of both :

Successfully written in the file...

Reading in a File

  • FileReader is useful to read data in the form of characters from a text file.
  • BufferedReader can be used along with FileReader to improve speed of execution.
  • FileInputStream is useful to read data from a file in the form of sequence of bytes.
  • FileInputStream is a subclass of InputStream.
  • BufferedInputStream can be used along with FileOutputStream to improve speed of execution.
Program 1:

import java.io.*;

class ReadingInFile {
    public static void main(String[] args) {
        try {
            FileReader myFReader = new FileReader("poem.txt");
            int data = myFReader.read();
            while (data != -1) {
                System.out.print((char) data);
                data = myFReader.read();
            }
            myFReader.close();
        } catch (IOException io) {
            System.out.println("File not found...");
        }
    }
}

Program 2:

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

class ReadingInFile {
    public static void main(String[] args) {
        try {
            FileReader myFReader = new FileReader("poem.txt");
            BufferedReader bReader = new BufferedReader(myFReader);
            int data = bReader.read();
            while (data != -1) {
                System.out.print((char) data);
                data = bReader.read();
            }
            bReader.close();
        } catch (IOException io) {
            System.out.println("File not found...");
        }
    }
}

Output of both :

You gave light to my soul
You helped me to be whole
I have felt love for you before
And it will be more and more,
You are mine, my dear
You are the angel from above
Who taught me how to love.
Please, forever keep me near.

- A poem by Writer

Deleting a File

  • To delete a file in Java, we use the delete() method of File class.
  • This method returns a Boolean value: true if and only if the file or directory is successfully deleted, else false.
import java.io.File;

class DeletingAFile {
    public static void main(String[] args) {
        File myFile = new File("MyTextFile.txt");
        myFile.delete();
    }
}

Comments