0% found this document useful (0 votes)
14 views

File IO streams

Uploaded by

mshivanshmaurya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

File IO streams

Uploaded by

mshivanshmaurya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Name of the School: School of Computer Science and

Engineering
Course Code: Course Name:Java Programming

DEPARTMENT OF COMPUTER SCIENCE


& ENGINEERING
Subject Name: Java Programming
Topics Covered: File Handling- I/O Stream- Character
Streams – Byte Streams

1
Faculty Name: Programe Name: B.Tech (CSE)
File handling in Java
File handling in Java refers to the process of reading from and writing to
files stored on a computer. Java provides several classes and methods to
perform operations like creating, reading, writing, and deleting files. These
operations are essential for managing data persistence in many applications,
as files can store data beyond the lifetime of a program's execution.
• The File class from the java.io package, allows us to work with
files.
• To use the File class, create an object of the class, and specify the
filename or directory name. • The File class is used for
creation of files and
directories, file searching,
Example: file deletion, etc.
• The File object represents
the actual file/directory on
the disk.

2
Creating a file
mport java.io.*;
ublic class filemethods {
ublic static void main(String[] args){

File f=new File("C:\\Users\\Admin\\Desktop\\JT.text");


try
{
if(f.createNewFile())
{
System.out.println("File is successfully created");
}
else {
System.out.println("File is already exists");
} Output:
}
catch(IOException i){ File is successfully created
or
System.out.println("Exception is handled"); File is already exists \\ if file is already created before
}} 3
Writing into a file Explanation:
To write into a file in Java, you can use the 1.FileWriter: This is the class used
FileWriter or BufferedWriter class from the to write characters to a file. It opens
the file and writes the content to it.
java.io package. Below is a simple example of 2.write(): This method writes the
how to write data into a file using FileWriter. specified content to the file.
3.close(): It is important to close
port java.io.FileWriter; the FileWriter to ensure that all
port java.io.IOException; content is written to the file and
resources are released.
blic class fileWriter {
public static void main(String[] args) throws IOException {
FileWriter f = new FileWriter("C:\\Users\\Admin\\Desktop\\JT.text");
f.write("Hello, World! Myself Jitender Tanwar\n");
//f.write("This is a Java program writing to a file.\n");
// Close the writer to save and release resources
f.close();
System.out.println("Data written to the file successfully!");
}}
4
Output:
Data written to the file successfully!
Writing into a file using BufferedWriter
If you plan to write large amounts of data to a file,
you may want to use a BufferedWriter, which
buffers characters to provide efficient writing.

import java.io.FileWriter;
import java.io.IOException;
public class fileWriter { Key Differences:
public static void main(String[] args) • FileWriter: Writes data directly to the file.
throws IOException { • BufferedWriter: Buffers the output to
BufferedWriter f = new improve performance, especially when
BufferedWriter("C:\\Users\\Admin\\Desktop\\ writing large amounts of text.
JT.text");
f.write("Hello, World! Myself Jitender
Tanwar\n");
//f.write("This is a Java program writing Both approaches work well for writing text data to
files, but using BufferedWriter is generally
to a file.\n");
recommended for performance reasons when writing
// Close the writer to save and release larger files.
resources
5
f.close();
File Class Methods

6
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class fileMethods {
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\Admin\\Desktop\\JT.text");
// Check if the file exists
if (f.exists()) {
// Display file information
System.out.println("File Information:");
System.out.println("Name: " + f.getName());
System.out.println("Path: " + f.getAbsolutePath());
System.out.println("Canonical Path: " + f.getCanonicalPath());
System.out.println("Is Directory: " + f.isDirectory()); Outpit:
System.out.println("Is File: " + f.isFile()); File Information:
Name: JT.text
System.out.println("Readable: " + f.canRead()); Path: C:\Users\Admin\Desktop\
System.out.println("Writable: " + f.canWrite()); JT.text
System.out.println("File Size: " + f.length() + " bytes"); Canonical Path: C:\Users\Admin\
Desktop\JT.text
System.out.println("Last Modified: " + f.lastModified()); Is Directory: false
} else { Is File: true
System.out.println("The file does not exist."); Readable: true
Writable: true
7 }}} File Size: 36 bytes
Last Modified: 1732777434631
The Java I/O API provides a rich set of classes and methods for handling
input and output operations. It can be broadly categorized into byte-based
and character-based streams.

1. Byte Streams:
Byte streams work with raw binary data. They read and write data byte-by-
byte. These are useful for handling all kinds of I/O, including images, audio
files, etc.

InputStream: The base class for reading byte data.


•FileInputStream: Reads bytes from a file.
•BufferedInputStream: Adds buffering for efficiency.

OutputStream: The base class for writing byte data.


•FileOutputStream: Writes bytes to a file.
•BufferedOutputStream: Adds buffering for efficiency.
8
2. Character Streams
Character streams work with characters and handle data as Unicode. They
are designed for reading and writing text data, ensuring that characters are
properly encoded and decoded.

Reader: The base class for reading character data.


•FileReader: Reads characters from a file.
•BufferedReader: Reads text efficiently by buffering input.

Writer: The base class for writing character data.


•FileWriter: Writes characters to a file.
•BufferedWriter: Buffers the output for efficient writing.

9
Key Classes and Interfaces in Java I/O
a) Byte Stream Classes
b) Character Stream Classes
1.InputStream (abstract class) 1.Reader (abstract class)
•FileInputStream: Reads bytes from a
• FileReader: Reads characters from a
file. file.
•BufferedInputStream: Reads bytes
• BufferedReader: Reads text efficiently.
with buffering. • InputStreamReader: Bridges byte
•DataInputStream: Reads primitive
streams to character streams.
data types. • StringReader: Reads characters from a
•ObjectInputStream: Reads objects.
string.
2.OutputStream (abstract class)
2.Writer (abstract class)
•FileOutputStream: Writes bytes to a • FileWriter: Writes characters to a file.
file. • BufferedWriter: Writes text with
•BufferedOutputStream: Writes bytes
buffering.
with buffering. • OutputStreamWriter: Bridges
•DataOutputStream: Writes primitive
character streams to byte streams.
data types. • StringWriter: Writes characters to a
•ObjectOutputStream: Writes objects.
10 string.
Example of Byte Stream:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamExample {
public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream("input.txt"); // Create a byte stream for reading from a file
FileOutputStream outputStream = new FileOutputStream("output.txt"); // Create a byte stream for writing to a file
int byteData;
while ((byteData = inputStream.read()) != -1) {// Read byte by byte and write it to the output file
outputStream.write(byteData);
}
inputStream.close(); // Close the streams
outputStream.close();
System.out.println("File copied successfully using byte streams.");
} catch (IOException e) {
e.printStackTrace();
11 } }}
Example of Character Stream:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharacterStreamExample {
public static void main(String[] args) {
try {
// Create a character stream for reading from a text file
FileReader reader = new FileReader("input.txt");
// Create a character stream for writing to a text file
FileWriter writer = new FileWriter("output.txt");
int charData;
while ((charData = reader.read()) != -1) {
// Read character by character and write it to the output
file
writer.write(charData);
}
// Close the streams
reader.close();
writer.close();
System.out.println("File copied successfully using
character streams.");
} catch (IOException e) {
e.printStackTrace();
12 } }}
Key Differences:

• Byte Stream: Used for all types of I/O, including binary data. Each read/write
operation works on a byte (8 bits).

• Character Stream: Specifically for text-based I/O, handling characters (16 bits).
It automatically handles character encoding/decoding (e.g., UTF-8, UTF-16).

13
Thank you

14

You might also like