0% found this document useful (0 votes)
0 views7 pages

Oops With Java (BCS403) Notes Chapter-9

Chapter 9 of 'Object Oriented Programming With JAVA' covers input and output operations in Java using the java.io package. It explains the concepts of byte and character streams, standard streams, and provides examples of reading from and writing to files using FileInputStream, FileOutputStream, FileReader, and FileWriter. Additionally, it discusses the File class for managing file and directory pathnames, including methods for checking file existence and attributes.

Uploaded by

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

Oops With Java (BCS403) Notes Chapter-9

Chapter 9 of 'Object Oriented Programming With JAVA' covers input and output operations in Java using the java.io package. It explains the concepts of byte and character streams, standard streams, and provides examples of reading from and writing to files using FileInputStream, FileOutputStream, FileReader, and FileWriter. Additionally, it discusses the File class for managing file and directory pathnames, including methods for checking file existence and attributes.

Uploaded by

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

Object Oriented Programming With JAVA

Chapter-9

Input & Output in Files

JAVA Input/Output
The java.io package in Java offers a
comprehensive collection of classes essential for Java Input/Output
handling input and output (I/O) operations. These Java Streams
streams effectively act as sources and destinations  Input Stream
 Output Stream
for data transfer. The classes within the java.io
Byte Stream
package is versatile, supporting a wide range of
Character Stream
data types including primitives, objects, and
Standard Streams
localized characters. Whether you're reading input Reading & Wri ng Files
from a file or sending output to a network, the FileOutputstream
java.io package has the tools you need to manage Java.io.File Class
Java I/O processes efficiently. File Object
Stream
In Java, a stream refers to a flow of data. There are
two primary types of streams:
InputStream: The Java InputStream class is the base
class for all input stream classes that handle bytes. It provides a way to read data in the form
of bytes. When creating a subclass of InputStream, you need to define a method that returns
the next byte of input. The reset() method can be used to move the stream back to a position
marked earlier in the data.
It is used for reading data from a source.
OutputStream: This abstract class is the base for all classes that handle output streams of
bytes. An output stream takes bytes and sends them to a destination. Any subclass of
OutputStream must include at least a method to write one byte of data. It is Used for writing
data to a destination.

Java offers robust and adaptable support for input and output (I/O) operations related to files
and networks. However, this guide focuses on the fundamental aspects of streams and I/O
operations. We will explore the most frequently used examples in detail.
Byte Streams
Java byte streams are essential for handling input and output operations with 8-bit
bytes. Among the various classes associated with byte streams, the most commonly utilized
are FileInputStream and FileOutputStream. Below is an example examplenstrating how these
two classes can be used to copy content from an input file to an output file.

Example
Object Oriented Programming With JAVA
import java.io. *;
public class MyProg {
public static void main(String []args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("inputfile.txt");
out = new FileOutputStream("outputfile.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null)
in.close();
}
if (out != null)
out.close();
}
}
Now let's have a file inputfile.txt with the following content −
This is sample copy file.
To proceed, compile the provided program and run it to generate an "outputfile.txt" file
that mirrors the content of "inputfile.txt." To achieve this, place the code in a file named
"MyProg.java" and follow these steps:

1. Open the command line or terminal.


2. Navigate to the directory containing "MyProg.java."
3. Compile the program by typing javac MyProg.java and press Enter.
4. Execute the program by typing java MyProg and press Enter.
By following these steps, you'll successfully create an "outputfile.txt" file with the same
content as "inputfile.txt."
Character Streams
Java Byte Streams handle the input and output of 8-bit binary data(bytes), while Java
Character Streams are designed for the input and output of 16-bit Unicode characters.
Among the numerous classes associated with character streams, the most commonly used
are FileReader and FileWriter. Although FileReader internally utilizes FileInputStream and
FileWriter uses FileOutputStream, the key distinction lies in their operation. FileReader reads
two bytes at a time, and FileWriter writes two bytes at a time. Here is the example that
examplenstrates how to use these two classes to copy data from an input file to an output
file:
Example
import java.io. *;
public class MyProg {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
Object Oriented Programming With JAVA
in = new FileReader("inputfile.txt");
out = new FileWriter("outputfile.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null)
in.close();
}if (out != null)
out.close();
}
}
Now let's have a file inputfile.txt with the following content –
This is sample copy file.
To proceed, compile and run the provided program. This will create an output.txt file
containing identical content to the input.txt file. Begin by placing the code in a file named
CopyFile.java and follow these steps:

Standard Streams
All programming languages feature capabilities for handling standard I/O
(Input/Output) operations. This means that a user's program can receive input from a keyboard
and generate output on a computer screen. Java, in particular, uses three primary standard
streams for these operations:

1. Standard Input - This stream is used to receive data input for the user's program,
typically through a keyboard. In Java, this standard input stream is represented by System.in.

2. Standard Output- This stream is responsible for displaying the output generated
by the user's program, usually on a computer screen, and is represented by System.out.

3. Standard Error - This stream outputs error messages generated by the user’s
program, often displayed on a computer screen, and is represented by System.err.

Below is a simple Java program that uses an InputStreamReader to read from the standard
input stream until the user enters the character ‘q’ to quit. Try entering characters and see how
it processes until you decide to exit.
Example
import java.io. *;
public class MyProg {
public static void main(String args[]) throws IOException {
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
Object Oriented Programming With JAVA
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
To execute this program, use commands on command prompt or terminal window.

Reading and Writing Files


A stream represents a sequence of data. An InputStream is utilized for reading data
from a source, while an OutputStream is employed for writing data to a destination. Below is
an overview of the class hierarchy designed for managing Input and Output streams.
Two essential Java streams you should know are FileInputStream and FileOutputStream. The
FileInputStream stream is primarily used for reading data from files. You can create objects of
this stream using the new keyword, and there are various constructors available to suit
different needs. For instance, one commonly used constructor allows you to create an input
stream object by passing the file name as a string. This makes it straightforward to read data
from files efficiently. Following constructor takes a file object to create an input stream object
to read the file. First we create a file object using File() method as follows-
File f = new File("C:/prog/MyProg");
InputStream f = new FileInputStream(f);
Object Oriented Programming With JAVA
Once you have an InputStream object, you can use several helper methods to read
from the stream or perform other operations. These methods can facilitate efficient data
processing and simplify stream management.
• ByteArrayInputStream
• DataInputStream

FileOutputStream

The FileOutputStream class in Java is essential for creating files and writing data to
them. When you use this stream, it will automatically create a file if one doesn't already exist,
allowing you to open it for output. Below are two constructors that you can use to instantiate
a FileOutputStream object:

1. Using a File Name String: This constructor accepts the file name as a string to
create a stream object for file writing:
OutputStream outputStream = new FileOutputStream("C:/prog/MyProg");

2. Using a File Object: First, generate a file object using the File() method, then use
the file object to create the output stream:
File file = new File("C:/prog/MyProg");
OutputStream outputStream = new FileOutputStream(file);

Once you have the OutputStream object, a variety of helper methods becomes available. These
methods can assist in writing data to the stream or executing other operations.
Following is the example to examplenstrate InputStream and OutputStream –
import java.io.*;
public class MyProg {
public static void main(String []args ) {
try {
byte bWrite [] = {10,20,30,40,50};
OutputStream os = new FileOutputStream("outputfile.txt");
for (int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("MyProg.java");
int size = is.available();
for(int i = 0; i < size; i++) {
System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}
Output:
Object Oriented Programming With JAVA

Java.io.File Class
The File class in Java provides an abstraction for file and directory pathnames,
accommodating the varied formats across different platforms. Since names of files and
directories differ from one platform to another, a simple string cannot fully capture their
complexity.
This class offers several functionalities to manage pathnames, including methods to
delete and rename files, create directories, list directory contents, and ascertain common
attributes of files and directories. Here are some key points about the File class:
a) It serves as an abstract representation of file and directory pathnames.
b) Pathnames can be absolute or relative, and you can retrieve the parent of an abstract
pathname by using the getParent() method.
c) To use the File class, you start by creating an object and passing either a filename or
directory name to it.
d) File systems might impose certain restrictions on operations such as reading, writing,
and executing, which are referred to as access permissions.
e) File class instances are immutable; once a File object is created, the abstract
pathname it represents does not change.
The File class is essential for effective management, understanding and utilizing of file and
directory in Java.
File Object
Creating a File object involves passing a String that specifies the file's name, or using
another File object. For instance, the following code:
File a = new File("c:\prog\MyProg.java");
This code snippet establishes an abstract file name for the "MyProg.java" file located in
the directory c:\prog. This is considered an absolute abstract file name.
Program to check if a file or directory physically exist or not.
import java.io.File;
class MyProg
{
public static void main(String[] args) {
String fname =args[0];
File f = new File(fname);
System.out.println("File name :"+f.getName());
System.out.println("Path: "+f.getPath());
Object Oriented Programming With JAVA
System.out.println("Absolute path:" +f.getAbsolutePath());
System.out.println("Parent:"+f.getParent());
System.out.println("Exists :"+f.exists());
if(f.exists())
{
System.out.println("Is writeable:"+f.canWrite());
System.out.println("Is readable"+f.canRead());
System.out.println("Is a directory:"+f.isDirectory());
System.out.println("File Size in bytes "+f.length());
}
}
}
Output:

You might also like