0% found this document useful (0 votes)
21 views57 pages

IOSTREAMSFILES

The document discusses streams in Java. It explains that streams allow for continuous flow of data and are used for input/output operations. There are two main types of streams - byte streams and character streams. Byte streams handle 8-bit data while character streams handle 16-bit Unicode characters. The key abstract classes for streams are InputStream, OutputStream for byte streams and Reader, Writer for character streams. Concrete subclasses implement stream reading and writing methods.

Uploaded by

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

IOSTREAMSFILES

The document discusses streams in Java. It explains that streams allow for continuous flow of data and are used for input/output operations. There are two main types of streams - byte streams and character streams. Byte streams handle 8-bit data while character streams handle 16-bit Unicode characters. The key abstract classes for streams are InputStream, OutputStream for byte streams and Reader, Writer for character streams. Concrete subclasses implement stream reading and writing methods.

Uploaded by

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

OBJECT

ORIENTED
PROGRAMMING
BY
S.NAVYA
ASSISTANT PROFESSOR
DEPARTMENT OF CSIT
Stream in java
• In java, the IO operations are performed using the concept of streams. Generally, a
stream means a continuous flow of data. In java, a stream is a logical container of
data that allows us to read from and write to it. A stream can be linked to a data
source, or data destination, like a console, file or network connection by java IO
system. The stream-based IO operations are faster than normal IO operations.

• The Stream is defined in the java.io package.


To understand the functionality of java streams,
look at the following picture.
CONTD..
• In java, the stream-based IO operations are performed
using two separate streams input stream and output
stream. The input stream is used for input operations,
and the output stream is used for output operations.
The java stream is composed of bytes.
• In Java, every program creates 3 streams automatically, and these streams
are attached to the console.
 System.out: standard output stream for console output operations.
 System.in: standard input stream for console input operations.
 System.err: standard error stream for console error output operations.
• The Java streams support many different kinds of data, including simple
bytes, primitive data types, localized characters, and objects.
• Java provides two types of streams, and they are as follows.
 Byte Stream
 Character Stream

Both character and byte streams essentially provides a


convenient and efficient way to handle data streams in
Java.
The following picture shows how streams are
categorized, and various built-in classes used by the
java IO system.
Byte Stream in java
• In java, the byte stream is an 8 bits carrier.
The byte stream in java allows us to
transmit 8 bits of data.
• In Java 1.0 version all IO operations were
byte oriented, there was no other stream
(character stream).
Contd..
• The java byte stream is defined by two abstract
classes, InputStream and OutputStream. The
InputStream class used for byte stream based input
operations, and the OutputStream class used for byte
stream based output operations.
– The InputStream and OutputStream classes have
several concreate classes to perform various IO
operations based on the byte stream.
The following picture shows the classes used for
byte stream operations.
InputStream class
• The InputStream class has defined as an abstract class, and it
has the following methods which have implemented by its
concrete classes.

S.No. Method with Description


1 int available()It returns the number of bytes that can
be read from the input stream.

2 int read()It reads the next byte from the input stream.

3 int read(byte[] b)It reads a chunk of bytes from the


input stream and store them in its byte array, b.

4 void close()It closes the input stream and also frees


any resources connected with this input stream.
OutputStream class
• The OutputStream class has defined as an abstract class, and it
has the following methods which have implemented by its
concrete classes.
S.No. Method with Description
1 void write(int n)It writes byte(contained in an
int) to the output stream.
2 void write(byte[] b)It writes a whole byte
array(b) to the output stream.
3 void flush()It flushes the output steam by
forcing out buffered bytes to be written out.

4 void close()It closes the output stream and also


frees any resources connected with this output
stream.
Reading data using
BufferedInputStream
• We can use the BufferedInputStream class to
read data from the console. The
BufferedInputStream class use a method
read( ) to read a value from the console, or
file, or socket.
Reading Data from Console
import java.io.*;
public class ReadingDemo {
public static void main(String[] args) throws IOException {
BufferedInputStream read = new
BufferedInputStream(System.in);
try {
System.out.print("Enter any character: ");
char c = (char)read.read();
System.out.println("You have entered '" + c + "'");
}
catch(Exception e) {
System.out.println(e); }
finally {
read.close();
} } }
Reading from a file
import java.io.*;
public class ReadingDemo {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream(new
File("C:\\Raja\\dataFile.txt"));
BufferedInputStream input = new
BufferedInputStream(fileInputStream);
try {
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
input.close(); } } }
Writing data using
BufferedOutputStream
• We can use the BufferedOutputStream class to
write data into the console, file, socket. The
BufferedOutputStream class use a method
write( ) to write data.
import java.io.*;
public class WritingDemo {
public static void main(String[] args) throws IOException {
String data = "Java tutorials by BTech Smart Class";
BufferedOutputStream out = null;
try {
FileOutputStream fileOutputStream = new
FileOutputStream(new File("C:\\Raja\\dataFile.txt"));
out = new BufferedOutputStream(fileOutputStream);

out.write(data.getBytes());
System.out.println("Writing data into a file is success!");

}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close(); } }}
Character Stream in java
• In java, when the IO stream manages 16-bit Unicode
characters, it is called a character stream. The unicode set is
basically a type of character set where each character
corresponds to a specific numeric value within the given
character set, and every programming language has a character
set.
– In java, the character stream is a 16 bits carrier. The
character stream in java allows us to transmit 16 bits
of data
Contd..
• The java character stream is defined by two abstract
classes, Reader and Writer. The Reader class used for
character stream based input operations, and the Writer
class used for character stream based output operations.
The Reader and Writer classes have
several concreate classes to perform various IO
operations based on the character stream.

The following picture shows the classes used for
character stream operations.
Reader class
• The Reader class has defined as an abstract
class, and it has the following methods which
have implemented by its concrete classes.

S.No. Method with Description


1 int read()It reads the next character from the
input stream.

2 int read(char[] cbuffer)It reads a chunk of


charaters from the input stream and store them
in its byte array, cbuffer.
3 int read(char[] cbuf, int off, int len)It reads charaters into a
portion of an array.

4 int read(CharBuffer target)It reads charaters into into the


specified character buffer.

5 String readLine()It reads a line of text. A line is considered to be


terminated by any oneof a line feed ('\n'), a carriage return ('\r'), or a
carriage returnfollowed immediately by a linefeed.

6 boolean ready()It tells whether the stream is ready to be read.

7 void close()It closes the input stream and also frees any resources
connected with this input stream
Writer class
• The Writer class has defined as an abstract
class, and it has the following methods which
have implemented by its concrete classes.

S.No. Method with Description


1 void flush()It flushes the output steam by
forcing out buffered bytes to be written out.

2 void write(char[] cbuf)It writes a whole


array(cbuf) to the output stream
3 void write(char[] cbuf, int off, int len)It writes a
portion of an array of characters.
4 void write(int c)It writes single character.
5 void write(String str)It writes a string.
6 void write(String str, int off, int len)It writes a portion
of a string.
7 Writer append(char c)It appends the specified
character to the writer.
8 Writer append(CharSequence csq)It appends the
specified character sequence to the writer
9 Writer append(CharSequence csq, int start, int end)It
appends a subsequence of the specified character
sequence to the writer.
10 void close()It closes the output stream and also frees any
resources connected with this output stream
Reading data using
BufferedReader
• We can use the BufferedReader class to read
data from the console. The
BufferedInputStream class needs
InputStreamReaderclass.
• The BufferedReader use a method read( ) to read a
value from the console, or file, or socket.

Example 1 - Reading from console
import java.io.*;
public class ReadingDemo {
public static void main(String[] args) throws
IOException {
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String name = "";
System.out.print("Please enter your name: ");
name = in.readLine();
System.out.println("Hello, " + name + "!");
} }
Example 2 - Reading from a file
import java.io.*;
public class ReadingDemo {
public static void main(String[] args) throws IOException {
Reader in = new FileReader();
try {
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
input.close(); } }
}
Writing data using FileWriter
• We can use the FileWriter class to write data
into the file. The FileWriter class use a method
write( ) to write data.
import java.io.*;
public class WritingDemo {
public static void main(String[] args) throws IOException {
Writer out = new FileWriter("C:\\Raja\\dataFile.txt");
String msg = "The sample data";
try {
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}
Console IO Operations in
Java
• Reading console input in java
• In java, there are three ways to read console input.
Using the 3 following ways, we can read input
data from the console.
• Using BufferedReader class
• Using Scanner class
• Using Console class

1. Reading console input using
BufferedReader class in java
• Reading input data using the BufferedReader class is the
traditional technique. This way of the reading method is
used by wrapping the System.in (standard input stream) in
an InputStreamReader which is wrapped in a
BufferedReader, we can read input from the console.
• The BufferedReader class has defined in the java.io
package.
import java.io.*;
public class ReadingDemo {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
String name = "";
try {
System.out.print("Please enter your name : ");
name = in.readLine();
System.out.println("Hello, " + name + "!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
in.close(); } } }
2. Reading console input using
Scanner class in java
• Reading input data using the Scanner
class is the most commonly used method.
This way of the reading method is used by
wrapping the System.in (standard input
stream) which is wrapped in a Scanner,
we can read input from the console.
The Scanner class has defined in
the java.util package.
import java.util.Scanner;
public class ReadingDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name = "";
System.out.print("Please enter your name : ");
name = in.next();
System.out.println("Hello, " + name + "!");
} }
3. Reading console input using
Console class in java
• Reading input data using the Console
class is the most commonly used method.
This class was introduced in Java 1.6
version.

The Console class has defined in


the java.io package.
import java.io.*;
public class ReadingDemo {
public static void main(String[] args) {
String name;
Console con = System.console();
if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
} } }
Writing console output in java

• In java, there are two methods to write console


output. Using the 2 following methods, we can
write output data to the console.
1.Using print() and println() methods
2.Using write() method

1. Writing console output using
print() and println() methods
• The PrintStream is a bult-in class that
provides two methods print() and println()
to write console output. The print() and
println() methods are the most widely used
methods for console output.
Both print() and println() methods
are used with System.out stream.
Contd..
• The print() method writes console output in
the same line. This method can be used
with console output only.
• The println() method writes console output in
a separate line (new line). This method
can be used with console ans
also with other output sources.

public class WritingDemo {
public static void main(String[] args) {
int[] list = new int[5];
for(int i = 0; i < 5; i++)
list[i] = i*10;
for(int i:list)
System.out.print(i); //prints in same line
System.out.println("");
for(int i:list)
System.out.println(i);//Prints in separate line

} }
2. Writing console output using
write() method
• Alternatively, the PrintStream class
provides a method write() to write console
output.
• The write() method take integer as
argument, and writes its ASCII equivalent
character on to the console, it
also accept escape sequences.
public class WritingDemo {
public static void main(String[] args) {
int[] list = new int[26];
for(int i = 0; i < 26; i++) {
list[i] = i + 65; }
for(int i:list) {
System.out.write(i);
System.out.write('\n');
} } }
Files in java
• The File is a built-in class in Java. In java,
the File class has been defined in the
java.io package. The File class represents
a reference to a file or directory. The File
class has various methods to perform
operations like creating a file or
directory, reading from a file,
updating file content, and
deleting a file or directory.
The File class in java has the following
constructors.
S.No. Constructor with Description
1 File(String pathname)It creates a new File instance by converting the given
pathname string into an abstract pathname. If the given string is the empty
string, then the result is the empty abstract pathname.

2 File(String parent, String child)It Creates a new File instance from a parent
abstractpathname and a child pathname string. If parent is null then the new
File instance is created as if by invoking thesingle-argument File constructor on
the given child pathname string.

3 File(File parent, String child)It creates a new File instance from a parent
abstractpathname and a child pathname string. If parent is null then the new
File instance is created as if by invoking thesingle-argument File constructor on
the given child pathname string.

4 File(URI uri)It creates a new File instance by converting the given file: URI
The File class in java has the following methods.
S.No. Methods with Description
1 String getName()It returns the name of the file or
directory that referenced by the current File object.

2 String getParent()It returns the pathname of the


pathname's parent, or null if the pathname does not name
a parent directory.

3 String getPath()It returns the path of curent File.

4 File getParentFile()It returns the path of the current


file's parent; or null if it does not exist.

5 String getAbsolutePath()It returns the current file or


directory path from the root.
6 boolean isAbsolute()It returns true if the current file is absolute, false otherwise.

7 boolean isDirectory()It returns true, if the current file is a directory; otherwise


returns false.
8 boolean isFile()It returns true, if the current file is a file; otherwise returns false.

9 boolean exists()It returns true if the current file or directory exist; otherwise
returns false.
10 boolean canRead()It returns true if and only if the file specified exists and can
be read by the application; false otherwise.
11 boolean canWrite()It returns true if and only if the file specified exists and the
application is allowed to write to the file; false otherwise.

12 long length()It returns the length of the current file.


13 long lastModified()It returns the time that specifies the file was last modified.

14 boolean createNewFile()It returns true if the named file does not exist and was
successfully created; false if the named file already exists.

15 boolean delete()It deletes the file or directory. And returns true if and only if the
16 void deleteOnExit()It sends a requests that the file or directory needs be deleted
when the virtual machine terminates.
17 boolean mkdir()It returns true if and only if the directory was created; false
otherwise.
18 boolean mkdirs()It returns true if and only if the directory was created, along
with all necessary parent directories; false otherwise.
19 boolean renameTo(File dest)It renames the current file. And returns true if and
only if the renaming succeeded; false otherwise.
20 boolean setLastModified(long time)It sets the last-modified time of the file or
directory. And returns true if and only if the operation succeeded; false otherwise.

21 boolean setReadOnly()It sets the file permission to only read operations; Returns
true if and only if the operation succeeded; false otherwise.

22 String[] list()It returns an array of strings containing names of all the files and
directories in the current directory.
23 String[] list(FilenameFilter filter)It returns an array of strings containing names
of all the files and directories in the current directory that satisfy the specified
filter.
24 File[] listFiles()It returns an array of file references containing names of all the
files and directories in the current directory.
25 File[] listFiles(FileFilter filter)It returns an array of file references containing
names of all the files and directories in the current directory that satisfy the
specified filter.
26 boolean equals(Object obj)It returns true if and only if the argument is not null
and is an abstract pathname that denotes the same file or directory as this abstract
pathname.
27 int compareTo(File pathname)It Compares two abstract pathnames
lexicographically. It returns zero if the argument is equal to this abstract
pathname, a value less than zero if this abstract pathname is lexicographically
less than the argument, or a value greater than zero if this abstract pathname is
lexicographically greater than the argument.

28 int compareTo(File pathname)Compares this abstract pathname to another


object. Returns zero if the argument is equal to this abstract pathname, a value
less than zero if this abstract pathname is lexicographically less than the
argument, or a value greater than zero if this abstract pathname is
lexicographically greater than the argument.
import java.io.*;
public class FileClassTest {
public static void main(String args[]) {
File f = new File("C:\\Raja\\datFile.txt");
System.out.println("Executable File : " + f.canExecute());
System.out.println("Name of the file : " + f.getName());
System.out.println("Path of the file : " +
f.getAbsolutePath());
System.out.println("Parent name : " + f.getParent());
System.out.println("Write mode : " + f.canWrite());
System.out.println("Read mode : " + f.canRead());
System.out.println("Existance : " + f.exists());
System.out.println("Last Modified : " + f.lastModified());
System.out.println("Length : " + f.length());
//f.createNewFile()
//f.delete();
//f.setReadOnly() } }
//list all the files in a directory including //the files present in all its subdirectories.
import java.util.Scanner;
import java.io.*;
public class ListingFiles {
public static void main(String[] args) {
String path = null;
Scanner read = new Scanner(System.in);
System.out.print("Enter the root directory name: ");
path = read.next() + ":\\";
File f_ref = new File(path);
if (!f_ref.exists()) {
printLine();
System.out.println("Root directory does not
exists!");
printLine();
} else {
String ch = "y";
while (ch.equalsIgnoreCase("y")) {
printFiles(path);
System.out.print("Do you want to open any sub-directory (Y/N):
");
ch = read.next().toLowerCase();
if (ch.equalsIgnoreCase("y")) {
System.out.print("Enter the sub-directory name: ");
path = path + "\\\\" + read.next();
File f_ref_2 = new File(path);
if (!f_ref_2.exists()) {
printLine();
System.out.println("The sub-directory does not exists!");
printLine();
int lastIndex = path.lastIndexOf("\\");
path = path.substring(0, lastIndex);
} } } }
System.out.println("***** Program Closed *****");
}
public static void printFiles(String path) {
System.out.println("Current Location: " + path);
File f_ref = new File(path);
File[] filesList = f_ref.listFiles();
for (File file : filesList) {
if (file.isFile())
System.out.println("- " + file.getName());
else
System.out.println("> " + file.getName());
} }
public static void printLine() {
System.out.println("----------------------------------------");
} }
fil
File Reading & Writing in
Java
• In java, there multiple ways to read data from
a file and to write data to a file. The most
commonly used ways are as follows.
• Using Byte Stream (FileInputStream and
FileOutputStream)
• Using Character Stream (FileReader and FileWriter)


File Handling using Byte Stream

• In java, we can use a byte stream to handle


files. The byte stream has the following built-
in classes to perform various operations on a
file.
• FileInputStream - It is a built-in class in java that
allows reading data from a file. This class has
implemented based on the byte stream. The
FileInputStream class provides a method read() to
read data from a file byte by byte.
• FileOutputStream - It is a built-in class in java that
allows writing data to a file. This class has
implemented based on the byte stream. The
FileOutputStream class provides a
method write() to write data to a file
byte by byte.
import java.io.*;
public class FileReadingTest {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("C:\\Raja\\Input-File.txt");
out = new FileOutputStream("C:\\Raja\\Output-File.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); }
System.out.println("Reading and Writing has been success!!!"); }
catch(Exception e){
System.out.println(e);
}finally {
if (in != null) {
in.close(); }
if (out != null) {
out.close(); } } } }
File Handling using Character Stream
• In java, we can use a character stream to handle files. The character stream
has the following built-in classes to perform various operations on a file.
• FileReader - It is a built-in class in java that allows reading data from a
file. This class has implemented based on the character stream. The
FileReader class provides a method read() to read data from a file
character by character.
• FileWriter - It is a built-in class in java that allows writing data to a file.
This class has implemented based on the character stream. The FileWriter
class provides a method write() to write data to a file character by
character.
import java.io.*;
public class FileIO {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("C:\\Raja\\Input-File.txt");
out = new FileWriter("C:\\Raja\\Output-File.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c); }
System.out.println("Reading and Writing in a file is done!!!"); }
catch(Exception e) {
System.out.println(e); }
finally {
if (in != null) {
in.close(); }
if (out != null) {
out.close(); } } } }

You might also like