Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » Java » Programs » IO » Java program for demonstrating file I/O
Suryateja Pericherla Categories: IO. No Comments on Java program for demonstrating file I/O
0
(0)

Aim

To write a program for demonstrating file IO using Java.

 

Theory

Almost all programs in Java require some input which is processed by the program and generates some output. Java provides an API in the form of packages namely java.io, and java.nio for dealing with I/O.

 

Both these packages contain various classes which can be used to read and write data to various sources like a console, file, peripheral device, or a socket.

 

Java handles transfer of data in the form of streams. A stream is a flow of data which is composed of bytes. So, the data is transferred continuously as a flow. Java creates three streams automatically which are attached to the console. They are:


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


  • out: Standard output stream
  • in: Standard input stream
  • err: Standard error stream

 

Reading data from a file

There are different ways for reading data from a text file which can be used for different types of applications. The multiple ways for reading data from a text file include using BufferedReader, FileReader, Scanner, etc.

 

Using BufferedReader class

This way of reading text from a file reads it as character input stream. It can buffer the text for efficient reading of lines, arrays, and characters. The buffer size can be left as default or can be changed base on our need.

 

Let’s see a program which uses BufferedReader class for reading and displaying the text in a file. In the below example, the text file name is “sample.txt”.

import java.io.*;
class Driver
{   
    public static void main(String[] args) throws Exception
    {
	File f = new File("sample.txt");
	BufferedReader br = new BufferedReader(new FileReader(f));
	String line;
	while((line=br.readLine()) != null)
	{
		System.out.println(line);
	}
    }
}
Java

 

Writing data to a file

There are different ways for reading data from a text file which can be used for different types of applications. The multiple ways for reading data from a text file include using BufferedWriter, FileWriter, FileOutputStream, etc.

 

Using BufferedWriter class

This way of writing text to a file writes it as a character output stream. It can buffer the text for efficient writing of lines, arrays, and characters. The buffer size can be left as default or can be changed base on our need.

 

Let’s see a program which uses BufferedWriter class for writing data to a file. In the below example, the text file name is “output.txt”.

import java.io.*;
class Driver
{   
    public static void main(String[] args) throws Exception
    {
		File f = new File("output.txt");
		BufferedWriter bw = new BufferedWriter(new FileWriter(f));
		String text1 = "Writing data to a text file.";
		String text2 = "This is a sample string to test writing to a file.";
		bw.write(text1);
		bw.write(System.lineSeparator());
		bw.write(text2);
		System.out.println("Data stored in the file successfully.");
		bw.close();
    }
}
Java

 

Pseudo code / Steps

Program 1

  1. Create a class to read the text from a file named “data.txt” and display the text on the screen.
  2. Use StringTokenizer class available in util package to find out number of words in the text read from the file in previous step.
  3. Display the count of words on the screen.

 

Program 2

  1. Create a class for storing the text into a file named “details.txt”.
  2. Create a class Student with appropriate variables and constructor.
  3. Read the student details of 5 students like name, age, and branch from keyboard and store this in the file on a single line by separating the details using commas.
  4. Finally, after storing the student details in the text file, display a message “data stored successfully” on the screen.

 

Programs

Program 1

import java.io.*;
import java.util.StringTokenizer;
class ReadFileDemo
{
	public static void main(String args[]) throws Exception
	{
		File f = new File("data.txt");
		BufferedReader br = new BufferedReader(new FileReader(f));
		StringTokenizer st;
		String line;
		int count = 0;
		while((line=br.readLine()) != null)
		{
			st = new StringTokenizer(line);
			count += st.countTokens();
			System.out.println(line);
		}
		System.out.println("Number of words = " + count);
		br.close();
	}
}
Java

 

Input and Output for program 1:

This is a sample text file.
File name is sample.
Welcome to Java programming.
Number of words = 14
Java

 

Program 2

import java.io.*;
import java.util.Scanner;
class Student
{
	String name;
	int age;
	String branch;
	Student(String name, int age, String branch)
	{
		this.name = name;
		this.age = age;
		this.branch = branch;
	}
}
class WriteFileDemo
{
	public static void main(String args[]) throws Exception
	{
		File f = new File("details.txt");
		BufferedWriter bw = new BufferedWriter(new FileWriter(f));
		Scanner s = new Scanner(System.in);
		for(int i=1; i<=5; i++)
		{
			System.out.println("Enter student " + i + " details:");
			System.out.println("Enter student name:");
			String name = s.next();
			System.out.println("Enter student age:");
			int age = s.nextInt();
			System.out.println("Enter student branch");
			String branch = s.next();
			Student st = new Student(name, age, branch);
			String line = st.name + "," + st.age + "," + st.branch;
			bw.write(line);
			bw.write(System.lineSeparator());
		}
		System.out.println("data stored successfully.");
		bw.close();
	}
}
Java

 

Input and Output for program 2:

Enter student 1 details:
Enter student name:
teja
Enter student age:
20
Enter student branch
cse
Enter student 2 details:
Enter student name:
ramesh
Enter student age:
19
Enter student branch
cse
Enter student 3 details:
Enter student name:
mahesh
Enter student age:
20
Enter student branch
ece
Enter student 4 details:
Enter student name:
rani
Enter student age:
20
Enter student branch
eee
Enter student 5 details:
Enter student name:
gayatri
Enter student age:
19
Enter student branch
it
data stored successfully.
Java

 

Contents of the file details.txt

teja,20,cse
ramesh,19,cse
mahesh,20,ece
rani,20,eee
gayatri,19,it
Java

 

Result

The concepts related to file I/O were understood and implemented successfully.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory