Module 4.2 - Java Programming

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 29

FILE PROCESSING

Files
• Secondary Storage Device
• Persistent Data – remains after program terminates
• File (Java) – Stream of Bytes
• End of File - End-of-file marker / count of byte
• Indicated by OS (Exception / Return value of method)
streams
Java I/O
• Java I/O (Input and Output) is used to process
the input and produce the output.
• Java uses the concept of a stream to make I/O
operation fast.
• The java.io package contains all the classes
required for input and output operations.
•  file handling in Java is performed by Java I/O
API.
Streams

• A stream is a sequence of data. In Java, a stream is


composed of bytes. It's called a stream because it is
like a stream of water that continues to flow.
• Byte-based Stream
– Java byte streams are used to perform input and output
of 8-bit bytes.
– Input & Output Data in Binary format
– Ex: 5  binary format / 101
• Character-based Stream
– Java Character streams are used to perform input and
output for 16-bit unicode.
– Sequence of characters
• Types of Files (how they are created?)
– Binary File
– Text File
Standard Streams
• Java can open a file by creating an object
• Constructor interacts with OS to open the file
• 3 Standard Stream objects associated with device
– System.in  Input bytes from keyboard
– System.out  Output character data to screen
– System.err  Output error message to screen
Example :
System.out.println("simple message");  
System.err.println("error message");  

int i=System.in.read(); //returns ASCII code of 1st character  
System.out.println((char)i); //will print the character  
Hierarchy of classes In Streams
java.io (package) – File Processing
• Stream classes
– FileInputStream (byte-based i/p from a file)
– FileOutputStream (byte-based o/p to a file)
– FileReader (char-based i/p from a file)
– FileWriter (char-based o/p to a file)
• Inherits from
– InputStream
– OutputStream
– Reader
– Writer
• Objects
– ObjectInputStream
– ObjectOutputStream
• Character-based Stream
– Scanner (i/p data from keyboard / file)
– Formatter (o/p data to text-based stream ex: S.O.P)
File (class)
• Retrieve information about File / Directory
• Can open the file or manipulate the file using this object
• 4 Constructors
– File (String file name / directory name)
– File (String path name (absolute / relative path), String
file/dir)
– File (File object, String parent dir / dir)
– File (URI object)
• URI – Uniform Resource Identifier – general form of URL
• URI – locating files – vary with OS
• file://C:/data.txt  windows
• file:/home/student/data.txt  UNIX/Linux
File output stream(Bytes)
File output stream(Streams)
File input stream
BufferedInputStream
ByteArrayInputStream
FileInputStream
• This stream is used for reading data from the files.
Objects can be created using the keyword new and
there are several types of constructors available.
• Following constructor takes a file name as a string to
create an input stream object to read the file −
InputStream f = new FileInputStream ("C:/java/hello");
• Following constructor takes a file object to create an
input stream object to read the file.
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Helper Methods
Sr.N Method & Description
o.
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method of
this file output stream is called when there are no more references to this stream.
Throws an IOException.

3 public int read(int r)throws IOException{}


This method reads the specified byte of data from the InputStream. Returns an int.
Returns the next byte of data and -1 will be returned if it's the end of the file.

4 public int read(byte[] r) throws IOException{}


This method reads r.length bytes from the input stream into an array. Returns the
total number of bytes read. If it is the end of the file, -1 will be returned.

5 public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream. Returns an int.
// Reading data from a file using FileReader
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
int ch;
FileReader fr=null;
try
{ fr = new FileReader("text"); }
catch (FileNotFoundException fe)
{ System.out.println("File not found"); }
// read from FileReader till the end of file
while ((ch=fr.read())!=-1)
System.out.print((char)ch);
fr.close();
}
}
FileOutputStream
• FileOutputStream is used to create a file and write data
into it. The stream would create a file, if it doesn't
already exist, before opening it for output.
• Here are two constructors which can be used to create
a FileOutputStream object.
• Following constructor takes a file name as a string to
create an input stream object to write the file −
OutputStream f = new FileOutputStream("C:/java/hello")
• Following constructor takes a file object to create an
output stream object to write the file.
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Helper methods
Sr.N Method & Description
o.

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system
resources associated with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.

3 public void write(int w)throws IOException{}


This methods writes the specified byte to the output stream.

4 public void write(byte[] w)


Writes w.length bytes from the mentioned byte array to the
OutputStream.
// Creating a text File using FileWriter
import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main(String[] args) throws IOException
{
// Accept a string
String str = "File Handling in Java using "+
" FileWriter and FileReader";

// attach a file to FileWriter


FileWriter fw=new FileWriter("output.txt");

// read character wise from string and write into FileWriter


for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));
System.out.println("Writing successful");
//close the file
fw.close();
}
}
Example
import java.io.*;
InputStream is = new
public class fileStreamTest {
FileInputStream("test.txt");
int size = is.available();
public static void main(String args[]) { for(int i = 0; i < size; i++) {

try { System.out.print((char)is.read() +
byte bWrite [] = {11,21,3,40,5}; " ");
OutputStream os = new }
is.close();
FileOutputStream("test.txt");
} catch (IOException e) {
for(int x = 0; x < bWrite.length ; x++)
{ System.out.print("Exception");
os.write( bWrite[x] ); // writes }
the bytes }
} }
os.close();
Example To store student details in a text file
import java.io.*;
class StudentRecords
{
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

public void addRecords() throws IOException


{
// Create or Modify a file for Database
PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter("studentRecords.txt",true)));
String name, Class, fname, mname, address, dob;
int age;
long telephoneNo;
String s;
boolean addMore = false;
// Read Data
do {
System.out.print("\nEnter name: ");
name = br.readLine();

System.out.print("Father's Name: ");


fname = br.readLine();

System.out.print("Mother's Name: ");


mname = br.readLine();

System.out.print("Address: ");
address = br.readLine();

System.out.print("Class: ");
Class = br.readLine();

System.out.print("Date of Birth (dd/mm/yy) : ");


dob = br.readLine();

System.out.print("Age: ");
age = Integer.parseInt(br.readLine());

System.out.print("Telephone No.: ");


telephoneNo = Long.parseLong(br.readLine());
// Print to File
pw.println(name);
pw.println(fname);
pw.println(mname);
pw.println(address);
pw.println(Class);
pw.println(dob);
pw.println(age);
pw.println(telephoneNo);

System.out.print("\nRecords added successfully !\n\nDo you want to add more records ?


(y/n) : ");
s = br.readLine();
if(s.equalsIgnoreCase("y"))
{
addMore = true;
System.out.println();
}
else
addMore = false;
}
while(addMore);
pw.close();
showMenu();
}
public void readRecords() throws IOException
{
try
{
// Open the file
BufferedReader file = new BufferedReader(new
FileReader("studentRecords.txt"));
String name;
int i=1;
// Read records from the file
while((name = file.readLine()) != null)
{
System.out.println("S.No. : " +(i++));
System.out.println("-------------");
System.out.println("\nName: " +name);
System.out.println("Father's Name : "+file.readLine());
System.out.println("Mother's Name : "+file.readLine());
System.out.println("Address: "+file.readLine());
System.out.println("Class: "+file.readLine());
System.out.println("Date of Birth : "+file.readLine());
System.out.println("Age: "+Integer.parseInt(file.readLine()));
System.out.println("Tel. No.: "+Long.parseLong(file.readLine()));
System.out.println();
}
file.close();
showMenu();
}
catch(FileNotFoundException e)
{
System.out.println("\nERROR : File not Found !!!");
}
}
public void clear() throws IOException
{
// Create a blank file
PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter("studentRecords.txt")));
pw.close();
System.out.println("\nAll Records cleared successfully !");
for(int i=0;i<999999999;i++);
// Wait for some time
showMenu();
}
public void showMenu() throws IOException
{
System.out.print("1 : Add Records\n2 : Display Records\n3 : Clear All Records\n4 : Exit\n\
nYour Choice : ");
int choice = Integer.parseInt(br.readLine());
switch(choice)
{
case 1:
addRecords();
break;
case 2:
readRecords();
break;
case 3:
clear();
break;
case 4:
System.exit(1);
break;
default:
System.out.println("\nInvalid Choice !");
break;
}
}
public static void main(String args[]) throws
IOException
{
StudentRecords call = new StudentRecords();
call.showMenu();
}
}

You might also like