0% found this document useful (0 votes)
2 views

Chapter 8

The document provides an overview of input-output handling in Java, detailing the classification of streams into input and output types, along with specific classes for byte and character streams. It explains the methods available for reading and writing data, as well as file handling through the java.io package. Additionally, examples are provided to illustrate the usage of various stream classes and file operations.

Uploaded by

2370197
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 8

The document provides an overview of input-output handling in Java, detailing the classification of streams into input and output types, along with specific classes for byte and character streams. It explains the methods available for reading and writing data, as well as file handling through the java.io package. Additionally, examples are provided to illustrate the usage of various stream classes and file operations.

Uploaded by

2370197
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

OBJECT ORIENTED PROGRAMMING WITH JAVA

Input-Output Handling in Java – I

Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Input-Output Streams in Java
Stream in Java
Keyboard Screen
Java treats flow of data as
Input stream
stream.
Mouse Printer
Java streams are classified into
two basic types, namely, input
Memory Java Program Memory
stream and output stream.

The java.io package contains a Disk Disk


large number of stream classes
to support the streams. Output stream
Network Network
Input and output streams
Input Stream
Reads
Source Program

(a) Reading data into a program

Output Stream
Program Source

(b) Writing data to a destination


Java Classes for I-O Streams
I-O stream classes in Java
Java provides java.io package which contains a large number of stream
classes to process all types of data
Byte stream classes
• Support for handling I/O operations on bytes

Character stream classes


• Supports for handling I/O operations on characters
Taxonomy: Java stream classes
Java Stream
Class

Byte Stream Character


Class Stream Class

Input Stream Output Reader Writer


Class Stream Class Class Class

Memory File Pipe Memory File Pipe


Java Input Stream Classes
Taxonomy: Java stream classes
Java Stream
Class

Byte Stream Character


Class Stream Class

Input Stream Output Reader Writer


Class Stream Class Class Class

Memory File Pipe Memory File Pipe


Java input streams classes
Java input stream classes
InputStream classes is used to read 8-bit bytes and supports a number
of input-related methods

• Reading bytes
• Closing streams
• Marking positions in streams
• Skipping ahead in streams
• Finding the number of bytes in stream
• and many more…
Some input stream methods
Method Description Example:
read( ) Read a byte from the input stream
DataInputStream
read(byte b[ ]) Read an array of bytes into b readShort( ) readDouble( )
readInt( ) readLine( )
read(byte b[ ], int n, int m) Reads m bytes into b starting from nth byte readLong( ) readChar( )
readFloat( ) readBoolean( )
available( ) Gives number of bytes available in the input
readUTF( )

skip(n) Skips over n bytes from the input stream

reset( ) Goes back to the beginning of the stream

close( ) Close the input steam


Example: Use of class InputStream
• Reading bytes
• int read() • Skipping ahead in a stream
• int read (byte b[]) long skip (long n)
• int read (byte b[], int off, int len)
• Marking positions in a stream
void mark (int limit)
• Closing streams void reset()
• void close() boolean markSupported()

• Finding the number of bytes in a stream


• int available()
Java Output Stream Classes
Taxonomy: Java stream classes
Java Stream
Class

Byte Stream Character


Class Stream Class

Input Stream Output Reader Writer


Class Stream Class Class Class

Memory File Pipe Memory File Pipe


Java output stream classes

OutputStream classes is used to write 8-bit bytes and supports a number


of input-related methods
• Writing bytes
• Closing streams
• Flushing streams
• etc.
Java output stream classes
Object

OutputStream

FileOutputStream ObjectOutputStream

PipedOutputStream ByteArrayOutputStream
FilterOutputStream

BufferedOutputStream PushbackOutputStream
DataOutputStream

DataOutput
Some methods in output stream classes
Method Description Example:
write ( ) Write a byte from the input stream DataOutputStream
write (byte b[ ]) Write all bytes in the array b to the writeShort( ) writeDouble( )

output steam writeInt( ) writeLine( )

writeLong( ) writeChar( )
write (byte b[ ], int n, int m) Write m bytes from array b starting
writeFloat( ) WriteBoolean( )
from nth byte
writeUTF( )
close( ) Close the output stream

flush( ) Flushes the output stream


Use of class OutputStream
Writing bytes

• void write (byte b)


• void write (byte b[])
• void write (byte b[], int off, int len)

Closing a stream

• void close()

Clearing a buffer

• void flush()
Character Stream Classes
Taxonomy: Java stream classes
Java Stream
Class

Byte Stream Character


Class Stream Class

Input Stream Output Reader Writer


Class Stream Class Class Class

Memory File Pipe Memory File Pipe


Character stream classes
Character stream classes is used to read and write characters and
supports a number of input-output related methods
Reader stream classes
• To read characters from files.
• In many way, identical to InputStream classes.

Writer stream classes


• To write characters into files.
• In many way, identical to OutputStream classes.
Reader stream classes
Object

Reader

BuffereedReader StringReader

CharArrayReader PipeReader

InputStreamReader FilterReader

File Reader PushbackReader


Writer stream classes
Object

Writer

BuffereedWriter StringReader

CharArrayWriter PipeWriter

FilterWriter PrintWriter

OutputStreamWriter

FileWriter
List of Important tasks and their Classes
Task Character Stream Class Byte Stream Class
Performing input operations Reader InputStream
Buffering input BufferedReader BufferedlnputStream
Keeping track of line numbers LineNumberReader LineNumberlnputStream
Reading from an array CharArrayReader ByteArrayInputStream
Translating byte stream InputStreamReader (none)
into a character stream
Reading from files FileReader FileInputStream
Filtering the input FilterReader FilterlnputStream
Pushing back characters/bytes PushbackReader PushbackInputStream
Reading from a pipe PipedReader PipedInputStream
Reading from a string StringReader StringBufferInputStream
Reading primitive types (none) DataInputStream
Performing output operations Writer OutputStream
Buffering output BufferedWriter BufferedOutputStream
Writing to an array CharArrayWriter ByteArrayOutputStream
Filtering the output FilterWriter FilterOutputStream
Translating character stream OutputStreamWriter (none)
into a byte stream
Writing to a file FileWriter FileOutputStream
Printing values and objects PrintWriter PrintStream
Writing to a pipe PipedWriter PipedOutputStream
Writing to a string StringWriter (none)
Writing primitive types (none) DataOutputStream
OBJECT ORIENTED PROGRAMMING WITH JAVA
Input-Output Handling in Java – II

Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Usage of I-O Stream Classes
Get input using DataInputStream class
Calculator Program
import java.io.*; System.out.flush();
class InterestCalculator tempString = in.readLine();
{ rateOfInterest =
public static void main(String args[ ] ) Float.valueOf(tempString);
{ System.out.print("Enter Number of Years:");
Float principalAmount = new Float(0); System.out.flush();
Float rateOfInterest = new Float(0); tempString = in.readLine();
int numberOfYears = 0; numberOfYears =
Integer.parseInt(tempString);
DataInputStream in = new // Input is over: calculate the interest
DataInputStream(System.in); int interestTotal =
String tempString; principalAmount*rateOfInterest*numberOfYears;
System.out.print("Enter Principal System.out.println("Total Interest = " +
Amount: "); interestTotal);
System.out.flush(); }
tempString = in.readLine(); }
principalAmount =
Float.valueOf(tempString);
System.out.print("Enter Rate of
Interest: ");
Files Handling in Java
Java File I/O
Java provides java.io package which includes numerous class definitions
and methods to manipulate file and flow of data ( called File I/O streams )

There are
File
FileInputStream
four major FileOutputStream
classes: RandomAccessFile
Using class File
Opening a File object
• There are three constructors
• Way 1:
•File myFile;
•myFile = new File(fileName); // Constructor 1
• Way 2:
•File myFile;
•myFile = new File (pathName, filename); // Constructor 2
• Way 3:
•File myFile;
•File myFile = new File(myDir, fileName); // Constructor 3
Using class File
Dealing with file names
• String getName()

• String getPath()

• String getAbsolutePath()

• String getParent()

• boolean renameTo(File newFilename)


Using class File
Testing a file
• boolean exists()
• boolean canWrite()
• boolean canRead()
• boolean isFile()
• boolean isDirectory()
• boolean isAbsolute()
Using class File
Getting file information
• long lastModified()
• long length()
• boolean delete()

Directory utilities
• boolean mkDir(File newDir)
• boolean mkDirs(File newDir)
• String [] list()
Checking Status of a File
Using class File: An example
public static void getPaths (File f ) throws IOException {
import java.io.File

class FileTest {
public static void main (String args [ ] ) throws IOException {

System.out.println ("Name : " + f. getName( ) );


File fileToCheck;
if (args.length > 0 ) {
for (int i = 0; i <

import java.io.File
args.length;i++ ) {

]); System.out.println ("Path : " + f. getPath ( ) );


fileToCheck = new File(args[ i

class FileTest { System.out.println ("Parent : " + f.getParent ( ) );


getNames (fileToChecks);

getInfo(fileToCheck);

} (String args [ ] ) throws IOException {


}

public static void main


}
else

File fileToCheck; public static void getInfo (File f ) throws IOException {


System.out.println (" Usage
: Java file test <filename (s) >);
}

if (args.length > 0 )if{ (f.exists ) {


System.out.print) ("File
for (int i = 0; i < args.length;i++ { exists ");
fileToCheck = new File(args[ i ]);
System.out.println (f.canRead( ) ? "and is readable" : "");
System.out.println ( f.canWrite( ) ? "and is writable" : "");
getPaths(fileToCheck); public static void getPaths (File f ) throws IOException {

("File is last modified : + f.lastModified( ));


System.out.println ("Name : " + f.
System.out.println
getInfo(fileToCheck); getName( ) );
System.out.println ("Path : " + f.

System.out.println ("File is " + f.length( ) + "bytes" );


getPath ( ) );

} f.getParent ( ) );
System.out.println ("Parent : " +

}
}

} public static void getInfo (File f ) throws IOException {


if (f.exists ) {

else else "and is readable" : "");


System.out.print ("File exists ");
System.out.println (f.canRead( ) ?

System.out.println ("System.err.println
Usage : Java file (" test
File <filename (s) >););
does not exist."
? "and is writable" : "");
System.out.println ( f.canWrite( )

System.out.println ("File is last

} modified : + f.lastModified( ));


System.out.println ("File is " +

}
f.length( ) + "bytes" );
}

} exist." );
else
System.err.println (" File does not

}
}
Reading a File
Example: class FileInputStream
{ System.out.println (" Remaining bytes :" + fin.available( ) );
{
class InputStreamTest
class InputStreamTest
public static void main (String args [ ] ) {
int size;

public static void main (String args


// To open a file input stream.
FileInputStream fin;
[ ] ) {
System.out.println
fin = new FileInputStream (" C:\WINDOWS\SYSTEM\SYSTEM.INI");
("Next ¼ is displayed : Using read( b[ ])");
size = fin.available( );

int size; byte b[] = new


// returns the number of bytes availablebyte[size/4];
if (fin.read (b) != b.length )
System.out.println("Total bytes ::" + size);
System.out.println ( " First ¼ is displayed : Using read( )");
// To open a file input stream.
for (int i = 0; i < size /4 ; i++ ) {

} System.err.println ("File reading error : ");


System.out.println ((char) fin.read( ) );

FileInputStream fin; else {


fin = new FileInputStream (" C:\WINDOWS\SYSTEM\SYSTEM.INI");
String temp = new String (b, 0, 0, b.length );
size = fin.available( ); // Convert the bytes into string
System.out.println (temp) ;
// returns the number of bytes available
System.out.println("Total bytes ::" + size);// display text string.
System.out.println ( " First ¼ is displayed : Using ("
System.out.println available:"+fin.available( ) );
Still)");
read(
System.out.println (" skipping ¼ : Using skip ( )" );
for (int i = 0; i < size /4 ; i++ ) { System.out.println (" Remaining bytes :" + fin.available( ) );

fin.skip(size/4); System.out.println ("Next ¼ is displayed : Using read( b[ ])");

System.out.println ((char) fin.read( ) );


byte b[] = new byte[size/4];

(" File remaining for read ::"


if (fin.read (b) != b.length )
System.out.println System.err.println ("File reading error : ");

}
else {

+fin.available( ) ); String temp = new String (b, 0, 0, b.length );


// Convert the bytes into

}
string
System.out.println (temp) ;

fin.close ( ); // Close the input stream


// display text string.
System.out.println (" Still available:"+fin.available( ) );
System.out.println (" skipping ¼ : Using skip ( )" );

} fin.skip(size/4);
System.out.println (" File remaining for read ::" +fin.available( ) );

}
}
fin.close ( ); // Close the input stream
}
}
Writing into a File
Example: Writing bytes into file
import java.io.*;
class WriteBytes {
public static void main(String args[]) {
cities[]={'D','E','L','H','I','\n','M','A','D','R','A','S','\n','L','O','N','D','O',
'N','\n'}; //Declare and initialize a byte array byte
FileOutputStream outfile=null; //create an output file stream
try {
outfile = new FileOutputStream("city.txt");
// Connect the outfile stream to "city.txt"
outfile.write(cities); //Write data to the stream
outfile.close();
}
catch(IOException ioe) {
System.out.println(ioe);
System.exit(-1);
}
}
}
Reading from a File
Example: Reading bytes from file
import java.io.*;
class ReadBytes {
public static void main (String args[]) {
FileInputStream infile = null; // Create an input file stream
int b;
try {
infile = new FileInputStream(args[O]);
// Connect infile stream to the required file
while((b = infile.read()) != -1) {
System.out.print((char)b); // Read and display data
}
infile.close();
}
catch(IOException ioe) {
System.out.println(ioe);
}
}
}
Copy a File into Other File
(CharacterStream Class)
Example: Reading/ writing characters
//Copying characters from one file into another while ((ch = ins.read()) != -1)
import java.io.*; {
class CopyCharacters outs.write(ch) ;
}
{
}
public static void main (String args[]) catch(IOException e) {
{ System.out.println(e);
//Declare and create input and output files System.exit(-1);
File inFile = new File("input.dat"); }
File outFile = new File("output.dat"); finally //Close files
{
FileReader ins = null; // Creates file stream ins
try {
FileWriter outs = null;
ins.close();
// Creates file stream outs outs.close();
try { }
ins = new FileReader (inFile) ; catch (IOException e) { }
// Opens inFile }
outs = new FileWriter (outFile) ; } // main
} // class
// Opens outFile
int ch; // Read and write till the end
Copying a File into Other File
(ByteStream Class)
Example: Copying bytes from one file to another
import java.io.*;
import java.io.*;
try {
class CopyBytes
class CopyBytes catch(FileNotFoundException e) {
//Connect infile to in.dat
{ infile = new System.out.println("File not
{
FilelnputStream("in.dat"); found");
public static
public static void
void main (String args[])
main (String args[]) }
//Connect outfile to out.dat
{
{ outfile = new catch(IOException e) {
FileOutputStream("out.dat"); System.out.println(e.
//Declare input
//Declare input and
and output
output file
file
//Reading bytes from in.dat getMessage());
streams
streams and writing to out.dat }
do { finally //Close files
FilelnputStream infile =
FilelnputStream infile null;
= null;

try { java.io.*;
{

import
catch(FileNotFoundException e) {
byteRead = (byte) infile.read()
//Input stream
//Input stream \\ try {
outfile.write(byteRea d);
FileOutputStream outfile = null;
FileOutputStream outfile = null; } infile.close(); infile.close();

System.out.println("File not while(byteRead != - outfile.close(); outfile.close();

class //Connect
CopyBytes infile to in.dat
//Output stream
stream 1);
//Output }
}
//Declare a
//Declare a variable
variable to
to hold
hold a
a catch(IOException e){}

found");
infile = new
byte }
byte

{
}

}
byte byteRead;
byte byteRead; }

FilelnputStream("in.dat");
catch(IOException {
public static void e) main (String args[])
//Connect outfile to out.dat
System.out.println(e.
{ outfile = new
getMessage());
//Declare input and output file streams
} FileOutputStream("out.dat");
finally
FilelnputStream //Close
infile = in.dat
files null;
//Reading bytes from
{
and
//Inputtrywriting
stream
{ to
\ out.dat
do {
FileOutputStream outfile = null;
infile.close();
byteRead = (byte)
outfile.close();
//Output stream infile.read()
}
outfile.write(byteRea d);
//Declare a variable to hold a byte
} catch(IOException e){}
} byteRead;
byte while(byteRead != - 1);
}
}}
Storing Data into a File
Example: Storing and reading data
import java.io.*;
class ReadWritePrimitive
dos.close();
{ fos.close();
public static void main (String args[]) throws IOException //Read data from the "prim.dat" file
{ FileInputStream fis = new FileInputStream(primitive);
File primitive = new File("prim.dat"); DataInputStream dis = new DataInputStream(fis);
FileOutputStream fos = new FileOutputStream(primitive); System.out.println(dis.ReadInt());
System.out.println(dis.ReadDouble());
DataOutputStream dos = new DataOutputStream(fos);
System.out.println(dis.ReadBoolean());
System.out.println(dis.ReadChar());
//Write primitive data to the "prim.dat"file
dos.WriteInt(1999); dis.close();
dos.WriteDouble(375.85); fis.close();
dos.WriteBoolean(false); }
dos.WriteChar('X'); }
Example: Storing and reading data in same file
importjava.io.*;
java.io.*; dos == new
dos new DataOutputStream(new
DataOutputStream(new FileOutputStream(intFile));
FileOutputStream(intFile)); try {
import
for(int i=0;i<20;i++)
for(int i=0;i<20;i++) dis = new DatalnputStream(new
classReadWriteIntegers
class ReadWriteIntegers ((int)
dos.writelnt ((int) (Math. random () *100));
random () *100)); }}
dos.writelnt (Math. FilelnputStream(intFile)); //Create input stream for intFile file
{{ catch(IOException ioe)
catch(IOException ioe) {{
System.out.println(ioe.getMessage());
System.out.println(ioe.getMessage()); for(int i=0;i<20;i++) {
publicstatic
public staticvoid
voidmain (String
main(String
int n = dis.readlnt();
args[])
args[]) }} System.out.print(n + " "); } }
finally
finally {{ catch(IOException ioe) {
{{ try {{
try System.out.println(ioe.
dis==null;
DatalnputStreamdis null;

import java.io.*;
DatalnputStream dos.close()
dos.close() getMessage());
}}
try {
//Inputstream
//Input stream }
catch(IOException ioe)
catch(IOException ioe) {{ }} finally {
dos==null;
DataOutputStreamdos
DataOutputStream null;
}}
class disReadWriteIntegers
try {

intFile==new
FileintFile new
DataOutputStream(new
//Outputstream
//Output stream
FileOutputStream(intFile));
= new DatalnputStream(new
//Reading integers
//Reading integers from
from rand.dat
rand.dat file
file
}
dis.close();
catch(IOException ioe)

{
File

for(int
{ }
File("rand.dat");
File("rand.dat");
//Writingintegers
integersto
torand.dat
rand.datfile
file i=0;i<20;i++)
FilelnputStream(intFile));
//Constructaafile
//Construct file
//Create input stream for intFile file }
}

main {(String
//Writing
try
try for(int
public static void((int)
i=0;i<20;i++)
dos.writelnt (Math. random () *100)); }
}

{{
int n = dis.readlnt();
catch(IOException
args[]) ioe) {
//Createoutput
//Create outputstream
streamfor
forintFile
intFilefile
file dos==new
dos new

{ System.out.print(n + " "); } }


System.out.println(ioe.getMessage());
catch(IOException ioe) {
} DatalnputStream dis = null;
System.out.println(ioe.
//Input
finally stream
{
getMessage());
} try { dos = null;
DataOutputStream
finally {
//Output stream
dos.close()
try intFile
File { = new
}
dis.close();
File("rand.dat"); //Construct a file
catch(IOException
} ioe) { }
//Writing integers to rand.dat file
} catch(IOException ioe){ }
} try
//Reading integers from rand.dat file
} {
} //Create output stream for intFile file
Merging two Files into a File
Example: Concatenation and buffering
import java.io.*;
class SequenceBuffer
{ //Create buffered input and output streams
BufferedlnputStream inBuffer = new
public static void main (String args[]) throws
BufferedlnputStream(file3);
IOException
BufferedOutputStream outBuffer = new
{ BufferedOutputStream(System.out);
//Declare file streams //Read and wri te till the end of buffers
FilelnputStream file1 = null; int ch;
FilelnputStream file2 = null; while((ch = inBuffer.read()) != -1)
outBuffer.write((char)ch);
inBuffer.close();
outBuffer.close();
SequencelnputStream file3 = null;
file1.close();
//Declare file3 to store combined files file2.close();
file1 = new FilelnputStream("text1.dat"); }
//Open the files to be concatenated }
file2 = new FilelnputStream("text2.dat");
//Open the files to be concatenated
file3 = new SequencelnputStream(filel,file2) ;
//Concatenate filel and file2
OBJECT ORIENTED PROGRAMMING WITH JAVA
Input-Output Handling in Java - III

Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Random Access Files in Java
Use of class RandomAccessFile
• As the name implies the class RandomAccessFile allows us to handle a
file randomly in contrast to sequentially in InputStream or
OutputStream classes

• It allows to move file pointer randomly

• Moreover, it allows read or write or read-write simultaneously.


Class: RandomAccessFile

Object

DataInput DataOutput

RandomAccessFile
Example: RandomAccessFile
import java.io.*; System.out.println(file.readlnt());
class RandomIO System.out.println(file.readDouble());
{ file.seek(2); // Go to the second item
public static void main (String args[)) System.out.println(file.readlnt());
{ // Go to the end and append false to
RandomAccessFile file = null; the file
try { file.seek(file.length());
file = new file.writeBoolean(false);
file. seek (4) ;
RandomAccessFile("rand.dat","rw");
System.out.println(file.readBoolean());
// Writing to the file
file.close();
file.writeChar('X');
}
file.writelnt(555);
catch(IOException e)
file.writeDouble(3.1412); {
file.seek (0);
// Go to the beginning System.out.println(e);
// Reading from the file }
System.out.println(file.readChar()); }
}
Example: Appending to a RAF
import java.io.*;
class RandomAccess
{
static public void main(String args[])
{
RandomAccessFile rFile;
try
{
rFile = new RandomAccessFile("city.txt","rw");

rFile.seek(rFile.lenght()); // Go to the end


rFile.writeByte("MUMBAI\n"); //Append MUMBAI
rFile.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}
Interactive Input-Output
Interactive input and output
// Writing to the file "invent.dat"
import java. util. *; // For using StringTokenizer
import java. util. *; // For using StringTokenizer class
import java.io.*;
class Inventory {
class
dos.writeInt(code);
import java.io.*; static DataInputStream din = new DataInputStream(System.in);

dos.writeInt(items);
static StringTokenizer st;
public static void main (String args[J) throws

class Inventory { IOException


{
dos.writeDouble(cost);
static DataInputStream din = new DataInputStream(System.in);
DataOutputStream dos = new DataOutputStream(new
FileOutputStream("invent.dat"));
// Reading from console
dos.close();
static StringTokenizer st;
System.out.println("Enter code number");
st = new StringTokenizer(din.readLine());
// Processing data from the file
int code = Integer.parseInt(st.nextToken());

public static void main (String args[J)DataInputStream


throws
System.out.println("Enter number of items");
st = new StringTokenizer(din.readLine());
dis=new DataInputStream(new
int items = Integer.parselnt(st.nextToken());

IOException System.out.println("Enter cost");

FileInputStream("invent.dat"));
st = new StringTokenizer(din.readLine());

{
double cost = new

int codeNumber = dis.readInt();


Double(st.nextToken()).doubleValue{};

DataOutputStream dos = new DataOutputStream(new


int totalItems = dis.readInt();
FileOutputStream("invent.dat")); double itemCost = dis.readDouble();
// Reading from console double totalCost = total Items * itemCost;
System.out.println("Enter code number");
dis.close();
st = new StringTokenizer(din.readLine());
// Writing to console
// Writing to the file "invent.dat"
dos.writeInt(code);

int code = Integer.parseInt(st.nextToken());


dos.writeInt(items);
dos.writeDouble(cost);

System.out.println(); dos.close();

System.out.println("Enter number of items");


// Processing data from the file

System.out.println("Code Number : " + codeNumber);


DataInputStream dis=new DataInputStream(new
FileInputStream("invent.dat"));

st = new StringTokenizer(din.readLine());
System.out.println("Item Cost : " + itemCost);
int codeNumber = dis.readInt();
int totalItems = dis.readInt();
double itemCost = dis.readDouble();

int items = Integer.parselnt(st.nextToken());


System.out.println("Total Items : " + totalItems);
double totalCost = total Items * itemCost;
dis.close();
// Writing to console
System.out.println("Enter cost"); System.out.println("Total Cost : " + totalCost);
System.out.println();
System.out.println("Code Number : " + codeNumber);

st = new StringTokenizer(din.readLine());
System.out.println("Item Cost : " + itemCost);

}
System.out.println("Total Items : " + totalItems);
System.out.println("Total Cost : " + totalCost);

double cost = new Double(st.nextToken()).doubleValue{};


}
}
}
Graphical Input-Output
Graphical input and output
Graphical input and output
import java.io.*;
import java.awt.*; number = new TextField(25);
class StudentFile extends Frame number = new TextField(25);
{ numLabel = new Label("Roll Number");
// Defining window components name = new TextField(25);
TextField number, name, marks; nameLabel = new Label ("Student Name");
Button enter, done; marks = new TextField(25);
Label numLabel, nameLabel, markLabel; markLabel = new Label("Marks");
DataOutputStream dos; enter = new Button("ENTER");
done = new Button("DONE");
// Initialize the Frame // Add the components to the Frame
public StudentFile() add(numLabel);
{ add(number);
super("Create Student File"); add(nameLabel);
} add(name);
// Setup the window add(markLabel);
public void setup() add(marks);
{ add(enter);
resize(400, 200); add(done);
setLayout(new GridLayout(4,2)); // Show the Frame
// Create the components of the Frame show();
Graphical input and output
// Open the file catch(IOException e) { }
try { // Clear the text fields
dos new DataOutputStream( new number.setText(" ");
FileOutputStream("student.dat")); name.setText(" ");
} marks.setText(" ");
catch(IOException e) { }
System.err.println(e.toString()); // Adding the record and clearing the
System.exit(1); TextFields
} public void cleanup()
} {
// Write to the file if(!number.getText(). equals(" ")) {
public void addRecord() { addRecord();
int num; }
Double d; try {
num = (new dos.flush();
Integer(number.getText())).intValue(); dos.close();
try { }
dos.writelnt(num); catch(IOException e) { }
dos.writeUTF(name.getText()); }
d = new Double(marks.getText());
dos.writeDouble(d.doubleValue());
}
Graphical input and output
// Processing the event if(event.target instanceof Button)
public boolean action(Event if(event.arg.equals("DONE")) {
event,Object o) cleanup();
{ System.exit(0);
if(event.target instanceof return true;
Button) }
if(event.arg.equals("ENTER")) { return super.handleEvent(event);
addRecord(); }
return true; // Execute the program
} public static void main (String args[])
return super.action(event, o); {
} StudentFile student = new StudentFile();
public boolean handleEvent(Event student.setup();
event) }
{ }
Another graphical Input/Output
import java.io.*; number = new TextField(25);
import java.awt.*; numLabel = new Label ("Roll Number");
class ReadStudentFile extends Frame name = new TextField(25);
{ nameLabel = new Label ("Student Name");
// Defining window components
marks = new TextField(25);
TextField number, name, marks;
markLabel = new Label("Marks");
Button next, done;
Label numLabel, nameLabel, markLabel; next new Button("NEXT");
DataInputStream dis; done = new Button("DONE");
boolean moreRecords = true; // Add the components to the Frame
add(numLabel);
// Initialize the Frame add(number);
public ReadStudentFile() add(nameLabel);
{ add(name);
// Setup the window add(markLabel);
public void setup()
add(marks);
{
add(next);
resize(400,200);
setLayout(new add(done);
GridLayout(4,2)); // Show the Frame
// Create the components of the Frame show();
// Open the file
Another graphical Input/Output
s = dis.readUTF();
try {
d dis.readDouble();
dis new DatalnputStream(new
number.setText(String.valueOf(n));
FilelnputStream("student.dat") name.setText(String.valueOf(s));
} marks.setText(String.valueOf(d));
catch(IOException e) }
{ catch(IOException ioe) {
System.err.println(e.toString()); System.out.println("IO ErrorN);
System.exit(1); System.exit(l);
} }
} }
// Read from the file // Closing the input file
public void readRecord() public void cleanup()
{ {
int n; try
String s; {
double d; dis.close();
try { }
n = dis.readlnt(); catch(IOException e) { }
}
Another graphical Input/Output
// Processing the event
public boolean action(Event event,Object o)
{
if(event.target instanceof Button)
if(event.arg.equals("NEXT"))
// Execute the program
readRecord(); public static void main (String
return true; args[])
} {
public boolean handleEvent(Event event) ReadStudentFile student =
{ new ReadStudentFile();
if(event.target instanceof Button) student.setup() ;
if (event.arg.equals ("DONE") || moreRecords == }
false){ }
cleanup();
System.exit(0);
return true;
}
return super.handleEvent(event);
}
Question to think…

• How Java helps programmers to develop


GUIs?
• How one can develop programs like Google?

You might also like