Files

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

UNIT-IV

Files: Reading data from files and writing data to files, Random Access File,

Applet: Applet class, Applet structure, Applet life cycle, sample Applet programs. Event
handling: event delegation model, sources of event, Event Listeners, adapter classes, inner
classes.
Introduction
Java has a concept of working with streams of data. Java program reads
sequences of bytes from an input stream (or writes into an output stream): byte
after byte, character after character, primitive after primitive. Java defines various
types of classes supporting streams, for example, InputStream or OutputStream.
There are classes specifically meant for reading character streams such as Reader
and Writer. A Java application opens a file by creating an object and associating a
stream of bytes with that object. 111

Input Output Classes


1. System.in: It stands for standard input stream. It gives the data to user’s
program and usually a keyboard is used as standard input stream.
2. System.out: It stands for standard output stream. It is used to output the data
produced by the user’s program and usually a monitor is used to standard output
stream.
3. System.err: It stands for standard error stream. It is used to output the error
data produced by the user’s program.
Hierarchy to I/O Streams

1. Input Stream – It reads data from the source.

2. Output Stream – It writes data to the destination.


The Stream Classes

InputStream : Abstract class containing methods for performing input


OutputStream : Abstract class containing methods for performing output
FileInputStream : Child of InputStream that provides the capability to read
from disk files
FileOutputStream : Child of OutputStream that provides the capability to write
to disk files
PrintStream : Child of FilterOutputStream, which is a child of
OutputStream; PrintStream handles output to a system’s standard (or default)
output device, usually the monitor
BufferedInputStream : Child of FilterInputStream, which is a child of
InputStream; BufferedInputStream handles input from a system’s standard (or
default) input device, usually the keyboard

Class constructors
Sr.No. Constructor & Description

1 InputStream() : Single Constructor

Class methods

Sr.No. Method & Description

1 int available() : This method returns an estimate of the number of


bytes that can be read (or skipped over) from this input stream
without blocking by the next invocation of a method for this input
stream.

2 void close() : This method closes this input stream and releases any
system resources associated with the stream.

3 void mark(int readlimit) : This method marks the current position


in this input stream.

4 boolean markSupported() : This method tests if this input stream


supports the mark and reset methods.

5 abstract int read() : This method reads the next byte of data from
the input stream.

6 int read(byte[] b) : This method reads some number of bytes from


the input stream and stores them into the buffer array b.

7 int read(byte[] b, int off, int len) : This method reads up to len
bytes of data from the input stream into an array of bytes.

8 void reset() : This method repositions this stream to the position at


the time the mark method was last called on this input stream.

9 long skip(long n) : This method skips over and discards n bytes of


data from this input stream.
Methods inherited

This class inherits methods from the following classes

−Java.io.Objec OutputStream

The Java.io.OutputStream class is the superclass of all classes representing an


output stream of bytes. An output stream accepts output bytes and sends them
to some sink.Applications that need to define a subclass of OutputStream must
always provide at least a method that writes one byte of output.

 Class declaration: Following is the declaration for Java.io.OutputStream class


−public abstract class OutputStream extends Objectimplements Closeable,
Flushable
 Class constructors
Sr.No. Constructor & Description

1 OutputStream() : Single Constructor.

 Class methods
Sr.No. Method & Description

1 void close() : This method closes this output stream and releases any
system resources associated with this stream.

2 void flush() : This method flushes this output stream and forces any
buffered output bytes to be written out.

3 void write(byte[] b) : This method writes b.length bytes from the


specified byte array to this output stream.
4 void write(byte[] b, int off, int len) :This method writes len bytes
from the specified byte array starting at offset off to this output
stream.

5 abstract void write(int b) : This method writes the specified byte to


this output stream.
// copy files model 1 finally {
import java.io.*; if (in != null) {
public class one in.close();
{ }
public static void main(String args[]) throws if (out != null)
IOException { { out.close();
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); } }

// copy files model 2 FileInputStream in=new


FileInputStream(filename1);
import java.io.*; FileOutputStream out=new
FileOutputStream(filename2);
class one int ch;
{ while((ch=in.read())!=-1)
public static void main(String []args) {
throws IOException out.write(ch);
{ }
in.close();
String filename1="input.txt"; out.close();
String filename2="output.txt"; }

try catch(IOException e)
{ {
System.out.println(e);
}}
}
Character Streams

Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode.
Though there are many classes related to character streams but the most
frequently used classes are, FileReader and FileWriter. Though internally
FileReader uses FileInputStream and FileWriter uses FileOutputStream but here
the major difference is that FileReader reads two bytes at a time and FileWriter
writes two bytes at a time.

//Copy files finally


{
import java.io.*; if (in != null)
class one {
{ in.close();
public static void main(String args[]) }
throws IOException { if (out != null)
FileReader in = null; { out.close();
FileWriter out = null; }
try }
{ }
in = new FileReader("input.txt"); }
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}
Standard Streams

All the programming languages provide support for standard I/O where the
user's program can take input from a keyboard and then produce an output on
the computer screen.
Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
Standard Output − This is used to output the data produced by the user's
program and usually a computer screen is used for standard output stream and
represented as System.out.
Standard Error − This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as System.err.
// keyboard input char c;
import java.io.*; do
class one {
{ c = (char) cin.read();
public static void main(String args[]) System.out.print(c);
throws IOException } while(c != 'q');
{ InputStreamReader cin = null; }
try
{ finally
cin = new {
InputStreamReader(System.in); if (cin != null)
System.out.println("Enter characters, { cin.close();
'q' to quit."); }
}}}
// copy files by line wise catch(FileNotFoundException ex)
import java.io.*; {
System.out.println("Unable to open file
class one '" + fileName + "'");
{ }
public static void main(String [] args)
{ String fileName = "temp.txt"; catch(IOException ex)
String line = null; {
try System.out.println("Error reading file '"
{ + fileName + "'");
FileReader fileReader = new // ex.printStackTrace();
FileReader(fileName); }
BufferedReader bufferedReader = new }
BufferedReader(fileReader); }
while((line =
bufferedReader.readLine()) != null)
{
System.out.println(line);
}
bufferedReader.close(); }
// count of characters {
import java.io.*; System.out.println(new String(buffer));
total += nRead;
class one }
{ inputStream.close();
public static void main(String [] args) System.out.println("Read " + total + "
{ bytes");}
String fileName = "temp.txt";
try catch(FileNotFoundException ex)
{ {
byte[] buffer = new byte[1000]; System.out.println("Unable to open file
FileInputStream inputStream = new '" + fileName + "'");
FileInputStream(fileName); }
int total = 0; catch(IOException ex)
int nRead = 0; {
while((nRead = System.out.println("Error reading file '"
inputStream.read(buffer)) != -1) + fileName + "'"); }}}
// Writing Text Files in Java BufferedWriter bufferedWriter =new
import java.io.*; BufferedWriter(fileWriter);
bufferedWriter.write("Hello there,");
class one bufferedWriter.newLine();
{ bufferedWriter.write("We are writing");
public static void main(String [] args) bufferedWriter.close();
{ }
String fileName = "temp.txt";
try catch(IOException ex)
{ {
FileWriter fileWriter = new System.out.println("Error writing to file
FileWriter(fileName); '" + fileName + "'");
}}}

// count of bytes catch(IOException ex)


import java.io.*; {
System.out.println("Error writing file '"+
class one fileName + "'");
{ }}}
public static void main(String [] args)
{
String fileName = "temp.txt";
try
{
String bytes = "Hello theren";
byte[] buffer = bytes.getBytes();
FileOutputStream outputStream =
new FileOutputStream(fileName);
outputStream.write(buffer);
outputStream.close();
System.out.println("Wrote " +
buffer.length + " bytes");
}
Random Access Files:

Using a random access file, we can read from a file as well as write to the file.
Reading and writing using the file input and output streams are a sequential
process.Using a random access file, we can read or write at any position within
the file. An object of the RandomAccessFile class can do the random file access.
We can read/write bytes and all primitive types values to a file.
RandomAccessFile can work with strings using its readUTF() and writeUTF()
methods. The RandomAccessFile class is not in the class hierarchy of the
InputStream and OutputStream classes.

Mode
A random access file can be created in four different access modes. The access
mode value is a string. They are listed as follows:

Mode Meaning

"r" The file is opened in a read-only mode.

"rw" The file is opened in a read-write mode. The file is created if it does not exist.

"rws" The file is opened in a read-write mode. Any modifications to the file's content and
its metadata are written to the storage device immediately.

"rwd" The file is opened in a read-write mode. Any modifications to the file's content are
written to the storage device immediately.
Read and Write
We create an instance of the RandomAccessFile class by specifying the file name
and the access mode.
RandomAccessFile raf = new RandomAccessFile("randomtest.txt", "rw");
A random access file has a file pointer that moves forward when we read data
from it or write data to it. The file pointer is a cursor where our next read or write
will start. Its value indicates the distance of the cursor from the beginning of the
file in bytes. We can get the value of file pointer by using its getFilePointer()
method. When we create an object of the RandomAccessFile class, the file
pointer is set to zero. We can set the file pointer at a specific location in the file
using the seek() method. The length() method of a RandomAccessFile returns the
current length of the file. We can extend or truncate a file by using its setLength()
method.

import java.io.File; Public static void


import java.io.IOException; incrementReadCounter(RandomAccessFile
fbghgggimport raf)throws IOException
java.io.RandomAccessFile; {
long currentPosition = raf.getFilePointer();
class one raf.seek(0);
{ int counter = raf.readInt();
public static void main(String[] args) counter++;
throws IOException raf.seek(0);
{ raf.writeInt(counter);
String fileName = raf.seek(currentPosition);
"randomaccessfile.txt"; }
File fileObject = new File(fileName);
if (!fileObject.exists()) public static void initialWrite(String
{ fileName) throws IOException
initialWrite(fileName); { RandomAccessFile raf = new
} RandomAccessFile(fileName, "rw");
readFile(fileName); raf.writeInt(0);
} raf.writeUTF("Hello world!");
raf.close();
public static void readFile(String }}
fileName) throws IOException
{
RandomAccessFileraf=new
RandomAccessFile(fileName, "rw"); int
counter = raf.readInt();
String msg = raf.readUTF();
System.out.println(counter);
System.out.println(msg);
incrementReadCounter(raf); raf.close();
}

You might also like