JAVA-Notes-Unit-3_Part 1
JAVA-Notes-Unit-3_Part 1
Files
Introduction to I/O Streams: Byte Streams, Character Streams. File I/O.
In Java, the java.io package provides the classes needed to work with I/O
operations. The primary classes in this package allow reading from and writing to files,
consoles, memory, and other data sources.
Stream: A stream in Java is an abstraction that allows you to read or write data in a
continuous flow. It represents the flow of data between your program and some
external source (like a file, network connection, or keyboard).
1. Byte Streams
2. Character Streams
1. Byte Streams:
o Byte Streams works with raw binary data and this is used to process data byte by
byte (8 bits).
o Used for handling raw binary data (e.g., image, audio, or video files).
o The basic classes for byte I/O are InputStream and OutputStream.
InputStream: Used to read bytes from an input source.
OutputStream: Used to write bytes to an output destination.
PrintStream This contains the most used print() and println() method
DataOutputStream This contains method for writing java standard data types.
try
{
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
System.out.print("Data Transferred successfully");
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
2. Character Streams:
PrintWriter This contains the most used print() and println() method
import java.io.FileReader;
B.Tech (CSE-DS)-II-II Sem Page 5
import java.io.FileWriter;
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-III
try
{
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
System.out.print("Data Transferred successfully");
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
File I/O
File I/O (Input/Output) operations in Java are crucial for reading from and
writing to files. Java provides a comprehensive set of classes in the java.io package
that enable file handling. These classes are capable of working with both text files and
binary files.