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

File Handling IO Basics

This document covers Java I/O, focusing on file handling using the File, FileInputStream, and FileOutputStream classes. It explains methods for reading and writing files, including character and byte streams, and provides example programs for various file operations. Additionally, it discusses console I/O using BufferedReader and PrintWriter, as well as the use of assertions in Java programming.
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)
27 views57 pages

File Handling IO Basics

This document covers Java I/O, focusing on file handling using the File, FileInputStream, and FileOutputStream classes. It explains methods for reading and writing files, including character and byte streams, and provides example programs for various file operations. Additionally, it discusses console I/O using BufferedReader and PrintWriter, as well as the use of assertions in Java programming.
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/ 57

UNIT IV

I/O, GENERICS, STRING


HANDLING
Presented by
Ms.G.Sakthi Priya, AP/CSE
File class
• 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
File Class
canRead() -Tests whether the file is readable or not
canWrite()- Tests whether the file is writable or not
createNewFile() - Creates an empty file
delete()- Deletes a file
exists() - Tests whether the file exists
getName() - Returns the name of the file
getAbsolutePath() - Returns the absolute pathname of the file
length() -the size of the file in bytes
list() - Returns an array of the files in the directory
mkdir() - Creates a directory
System.out.println("Enter the file name");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
File f1= new File(s);
System.out.println("File name: "+f1.getName());
System.out.println(f1.exists()?"exists":"Does not exist");
if(f1.exists())
{
if(f1.canRead()&&f1.canWrite())
{
System.out.println("File is both Readable and Writable.");
}
else if(f1.canRead())
{
System.out.println("Readable: "+f1.canRead());
}
else if(f1.canWrite())
{
System.out.println("Writable: "+f1.canWrite());
}
I/O Basics
• Java I/O (Input and Output) is used to process the input and produce
the output based on the input.
• Java uses the concept of stream to make I/O operation fast.
• The java.io package contains all the classes required for input and
output operations. We can perform file handling in java by java.io API.
Stream
• A stream is an abstraction that either produces or consumes
information.
• A stream is linked to a physical device by the Java I/O system.
• Input stream: disk file, a keyboard, or a network socket.
• Output stream: console, a disk file, or a network connection
Streams
Types of stream
• Byte streams provide a convenient means for handling input and
output of bytes.
• For example, when reading or writing binary data
• Deals with 8 bits of data

• Character streams provide a convenient means for handling input and


output of characters
• Deals with 16 bits of data (2 bytes of data at a time)
Reading and writing
Files
(Byte Stream)
Byte Stream
• Byte streams are defined by using two class hierarchies.

• At the top are two abstract classes InputStream and OutputStream

• Two of the most important are read( ) and write( ), which read and
write bytes of data.
FileInputStream
• FileInputStream in Java is a class that allows you to read bytes from a file. It's part
of the I/O (Input/Output) classes provided by Java to handle file operations.
• We can create an instance of this class by supplying a File or a path name, using
these two constructors:
1. FileInputStream(File file)
Example:
File f = new File(“Sample.txt”);
FileInputStream fin = new FileInputStream(f);

2.FileInputStream(String name)
FileInputStream fin = new FileInputStream(“sample.txt”);
Methods implemented by FileInputStream class
Methods Description
int available() returns an estimate of the number of remaining bytes that can be read.

int read() reads one byte of data, returns the byte as an integer value.
Return -1 if the end of the file is reached
int read(byte[]) reads a chunk of bytes to the specified byte array, up to the size of the
array. This method returns -1 if there’s no more data or the end of the file
is reached.
int read(byte[], int offset, reads up to length bytes of data from the input stream.
int length)

long skip(long n) skips over and discards n bytes of data from the input stream. This method
returns the actual number of bytes skipped.
void close() Closes this file input stream and releases any system resources associated
with the stream.
• Almost all methods throw IOException so remember to handle or
declare to throw it in your code.
Write a program to read and display
the file contents using ByteStream
class
import java.io.*;
public class ReadFile {
public static void main(String args[]) {
try{
FileInputStream in = new FileInputStream(“example.txt”);
int c;
while((c=in.read())!=-1){
System.out.println((char)c);
}
}
catch(FileNotFoundException e){
System.out.println(e.getMessage());
}
catch(IOException e){
System.out.println(e.getMessage());
}
} // end of main
} // end of class
Explanation
• Creates a FileInputStream object named in to read the file "example.txt".
FileInputStream in = new FileInputStream("example.txt");
• Reads the file content byte by byte using in.read() method until the end of the file (-1)
is reached.
• For each byte read, it converts the integer value to a character and prints it to the
console.
System.out.println((char)c);
• If the file "example.txt" is not found, it catches a FileNotFoundException and prints its
error message.
• If there is any error in reading a file, it catches a IOException and prints its error
message.
FileOutputStream

The FileOutputStream is a byte output stream class that provides methods


for writing bytes to a file.

We can create an instance of this class by supplying a File or a path name,


and/or specify to overwrite or append to an existing file, using the following
constructors
1. FileOutputStream(String name) Constructors of FileOutstream Class
Example:
FileOutputStram f = new FileOutputStream("output.txt");

2. FileOutputStream(String name, boolean append): if append is true, then the bytes will be written to the
end of an existing file rather than the beginning.
Example:
FileOutputStream f = new FileOutputStream("output.txt", true);

3. FileOutputStream(File file)
Example:
File f = new File("output.txt");
FileOutputStream fout = new FileOutputStream(f);

4. FileOutputStream(File file, boolean append)


Example:
File f = new File("output.txt");
FileWriter fout = new FileWriter(f, true); // Appends to file if it exists
Methods implemented by FileOutputStream class
Methods Description
void write(int) writes the specified byte to the output stream.

void writes the specified array of bytes to the output


write(byte[]) stream.
void write(byte[], writes length bytes from the specified byte array starting at offset to
int offset, the output stream.
int length)

void close() Closes this file output stream and releases any system resources
associated with the stream.
Write a program to get the string
from the user and write in a file
using ByteStream class
import java.util.*;
import java.io.*;
public class FileOutputStreamExample {
public static void main(String[] args) {
String s;
Scanner sc=new Scanner(System.in);
System.out.println("Enter data to be written in file");
s = sc.nextLine();
try {
FileOutputStream f= new FileOutputStream("output.txt");
byte[] arr = s.getBytes();
f.write(arr);
f.close();
System.out.println("Data has been written to the file.");
}
catch (IOException e) {
e.printStackTrace();
}
} //end of main
} // end of class
Write a program to copy from one file to another using Byte
Stream classes – FileInputStream & FileOutputStream.

import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
Count the number of characters,
words and lines in a file
import java.io.*;
class FileDemo{
public static void main(String[] args){
try{
FileInputStream in = new FileInputStream("sample.txt");
int c = in.read();
int charcount =0;
int linecount =0;
int wordcount =0;
while(c!=-1){
charcount++;
c = in.read();

if(c==32 || c==10){
wordcount++;
}

if(c==10){
linecount++;
}
}
System.out.println("char count "+charcount);
System.out.println("Word count "+(wordcount+1));
System.out.println("Line count "+(linecount+1));
in.close();

}
catch(IOException e){
}
}
}
Reading and writing
Files
(Character Stream)
Character Stream
• Character streams are defined by using two class hierarchies
• Reader and Writer
• The character stream classes are in java.io package
FileReader
• FileReader is another class in Java used for reading characters from a
file rather than bytes
• It's a subclass of InputStreamReader that reads data in the form of
characters from a file in a file system.
Constructor of FileReader class:
1. FileReader(File file): This constructor takes a File object representing
the file to be read and creates a FileReader object associated with that
file.
Example:
File file = new File("example.txt");
FileReader fileReader = new FileReader(file);

2. FileReader(String fileName): This constructor takes a String parameter


representing the path of the file to be read and creates a FileReader
object associated with that file
Example:
FileReader f = new FileReader("example.txt");
Methods implemented by FileReader

Methods Description
int read() reads a single character and returns the
character as an integer value.
int read(char[] cbuf) reads characters to an array and returns the number of characters
read.
int read(char[] cbuf, int offset, reads characters to a portion of an array and returns the number
int length) of characters read.
int read(CharBuffer target) reads characters into a character buffer and returns the number of
characters added to the buffer.
Write a program to read and display
the file contents using
CharacterStream class
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
try {
FileReader f = new FileReader("example.txt");
int c;
while ((c = f.read()) != -1) {
System.out.print((char) c);
}
f.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}
FileWriter
• FileWriter is used for writing characters to a file. It's a subclass of
OutputStreamWriter that writes character-based data to a file in the file system.
Constructors:
1. FileWriter(String fileName): This constructor creates a FileWriter object associated
with the file specified by the given file name.
Example:
FileWriter f = new FileWriter("output.txt");

2. FileWriter(String fileName, boolean append): This constructor creates a FileWriter


object associated with the file specified by the given file name. The append
parameter specifies whether data will be appended to the file if it already exists
(true), or if it will overwrite the existing content (false).
Example:
FileWriter f = new FileWriter("output.txt", true); // Appends to file if it exists
3. FileWriter(File file): This constructor creates a FileWriter object associated
with the given File object.
Example:
File f = new File("output.txt");
FileWriter fout = new FileWriter(f);

4. FileWriter(File file, boolean append): This constructor creates a FileWriter


object associated with the given File object. The append parameter specifies
whether data will be appended to the file if it already exists (true), or if it
will overwrite the existing content (false).
Example:
File f = new File("output.txt");
FileWriter fout = new FileWriter(f, true); // Appends to file if it exists
Methods implemented by FileWriter
class
Methods Description
write(int c) writes a single character.
write(char[] cbuf, int offset, int length) writes a portion of an array of characters.

write(char[] cbuf) writes an array of characters.

write(String str) writes a String.


write(String str, int offset, int length) writes a portion of a String
Write a program to get the string from the user
and write in a file using CharacterStream class
import java.util.*;
import java.io.*;
public class WriteExample {
public static void main(String[] args) {
String s;
Scanner sc=new Scanner(System.in);
System.out.println("Enter data to be written in file");
s = sc.nextLine();
try {
FileWriter f= new FileWriter("output.txt");
f.write(s);
f.close();
System.out.println("Data has been written to the file.");
}
catch (IOException e) {
e.printStackTrace();
}
} //end of main
} // end of class
Reading and writing
console I/O
Reading from Console –
BufferedReader class
• console input is accomplished by reading from System.in
• InputStreamReader is a class, which converts bytes to characters
• BufferedReader is a class reads text from a character-input stream,
buffering characters so as to provide for the efficient reading of characters
BufferedReader class
• This is the Java classical method to take input, Introduced in JDK1.0. This 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
user in the command line.

• Reads text from a character-input stream, buffering characters to provide for the efficient reading of characters, arrays,
and lines.

• The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

• In general, each read request made of a Reader causes a corresponding read request to be made of the underlying
character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read()
operations may be costly, such as FileReaders and InputStreamReaders. For example,

• BufferedReader in = new BufferedReader(new FileReader("foo.in"));

Advantages: The input is buffered for efficient reading.

Drawback: The wrapping code is hard to remember


Reading from Console
import java.io.*;
class Test
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine(); //reading string
System.out.println(name);
char c = (char) reader.read(); //reading character
System.out.println(c);
}
}
Writing to Console – PrintWriter
class
• Console output is accomplished by System.out
• PrintWriter is a class in Java used for writing formatted text to various
output streams
• Syntax: PrintWriter(OutputStream outputStream, boolean flushingOn)
• PrintWriter supports both print and println method to write
flushingOn controls whether Java flushes the output stream every time a println( )
method is called.
Writing to Console – PrintWriter
class
import java.io.*;
class Example{
public static void main(String[] args) {
PrintWriter writer = new PrintWriter(System.out,true);
writer.println("Hello, PrintWriter!");
writer.printf("This is a formatted %s", "line");
}
}
Assertion
• Condition that should be true during the execution of the program.
• Assertions are often used during testing to verify that some expected
condition is actually met.
• The assert keyword has two forms
1. assert condition;
condition is an expression that must evaluate to a Boolean result.
If the result is true, then the assertion is true and no other action takes place.
If the condition is false, then the assertion fails and a default AssertionError
object is thrown
2. assert condition: expr ;
expr is a value that is passed to the AssertionError constructor.
This value is converted to its string format and displayed if an assertion fails
Output
• If assert n > 0 : "n is not positive!"; is given in the code then output
will be
Previous years University Questions
Part A
• How character streams are defined?
Part B
Part C

You might also like