Professional Documents
Culture Documents
Files
Files
Files
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
Class constructors
Sr.No. Constructor & Description
Class methods
2 void close() : This method closes this input stream and releases any
system resources associated with the stream.
5 abstract int read() : This method reads the next byte of data from
the input stream.
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.
−Java.io.Objec OutputStream
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.
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.
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 + "'");
}}}
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
"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.