Professional Documents
Culture Documents
Types of data:
values, characters, image files sound files
InputStreams Hierarchy
InputStream
FileInputStream FilterInputStream
AbstractClass
extends
Streams: An Intro...
Create Streams
Add data java streams to stream read char(byte) from stream read char(byte) from stream
reading end
InputStreams are those streams that have a reading end and the writing end is connected to a source which supplies data (e.g. a HARD DISK).
InputStream Class
class Name InputStream public abstract int read() methods int read(byte b[]) int read(byte b[], int off, int len) long skip(long n) int available() void close() void mark(int readlimit) void reset() boolean markSupported()
FileInputStream Class
class Name FileInputStream extends InputStream public FileInputStream(File) methods FileInputStream(FileDescriptor) FileInputStream(String) native int read() native long skip(long n) native int available() native void close() int read(byte b[]) int read(byte b[], int off, int len)
void mark(int)
int read()
InputStream
extends
void close()
int read()
long skip(long n)
Using FileInputStream...
Writing end
reading end
fis = new FileInputStream ();
fis is the handle to the stream. One fis.read() will only read from
HD
can file read from this stream the only in the hard disk(HD)
Example
Read from file ( given as string in the command line ) then display contents on the console
Eg.FileInputDemo.java
OutputStreams Hierarchy
OutputStream
FileOutputStream FilterOutPutStream
AbstractClass
extends
OutputStream Class
class Name OutputStream public abstract void write(int); methods void write(byte[]); void write(byte[], int, int); void flush(); void close();
FileOutputStream Class
class Name FileOutputStream extends OutputStream public FileOutputStream(String); methods FileOutputStream(String,boolean); FileOutputStream(File); FileOutputStream(FileDescriptor); native void write(int); native void close(); void write(byte[]); void write(byte[], int, int); FileDescriptor getFD();
FileOutputStream...
reading end
writing end
HD
Example
Read form the console and Write it to a file (given as string in the command line).
Eg: FileOutputDemo.java
Class File
Uses of File class :
To extract information about files and directories of the local file system construct an object and use its methods to obtain information about the files/dirs on the local file system
Class java.io.File
class Name File public File (String thePath) methods File (String , String fname) File (File dir, String fname) String getAbsolutePath() String getCanonicalPath() boolean exists()/ canRead()/canWrite() long length()/lastModified(); boolean isFile()/isDirectory() boolean delete()/ renameTo(File)
Exercise
Write an application in java to display list of the directories or file contents of the specified path Textfield should be present at the top, in which we can specify the file path. Once the file/dir in the textfield is Eg FileTest.java specified. It should display info about the same in a textArea which is present
ByteArrayOutputStreams
application
boas
ByteArrayOutputStream
Internal storage
ByteArrayInputStream
application 143 54
bais
protected InputStream in Implements all methods by calling the methods of the stream using handle in
public int read() throws IOException { InputStream return in.read();} interface DataInput
FilterInputStream
buffers input
BufferedInputStream LineNumberInputStream give line nums for chars:deprecated
DataInputStream
PushbackInputStream
allow bytes to be sent back to stream
InputStreams
Streams available and their functionality application application
FileInputStream ByteArrayInputStream
Hard Disk
Array of bytes
BufferedInputStream
application
bis
BufferedInputStream bis=new fis BufferedInputStream (fis); BufferedInputStream bis.read() FileInputStream Hard Disk
Require a parameter
E.g BufferedTextInputTest.java
BufferedInputStream Class
class Name BufferedInputStream extends FilterStream public BufferedInputStream(InputStream) methods BufferedInputStream(InputStream,int) int available() long skip(long n) Allows the use of mark, reset and void close() other methods on void mark(int) the inputstream void reset() int read(byte b[]) int read(byte b[], int off, int len)
Example
Read one fourth from file ( given as string in the command line ), and then display contents on the console. Reset it and then display the first one fourth of the Eg: TestBufferedStream.java contents again on the console.
DataInput boolean readBoolean() float readFloat() long readLong() short readShort() String readUTF() double readDouble() int readUnsignedByte() DataInputStream int readInt() int read(byte b[])
char readChar()
int read(byte b[], int off, int len ) byte readByte() String readLine()
int readUnsignedShort()
DataInput/OutputStreams
Read and write primitive data types in bit streams (actually stored as bytes) read and write in a machine independent way Data must be written and read in the same order
DataInput/OutputStreams
FileInputStream fis=new FileInputStream (testdata.dat); FileOutputStream fos=new FileOutputStream (testdata.dat); DataOutputStream dos=new DataOutputStream (fos); DataInputStream dis=new DataInputStream (fis); System.out.println(dis.readBoolean()); dos.writeboolean(true); dos.close(); fos.close();
Example
Write a program to write the following information to a file named testItem.dat (items separated by tabs)
25.99 345.32
12 6
Write a second program to read and display the above information from the file testItem.dat
PrintStream
Deprecated use PrintWriter instead
Class System
An uninstantiable System class that provides a lot of important methods (all static) and references for other objects
InputStream in OutputStream out OutputStream err exit() gc() arrayCopy getProperties
application br
BufferedReader br=new BufferReader( new InputStreamReader(System.in) ); String str = br.readLine() //process to obtain an integer int i = Integer.parseInt(str);
Operating System
Normal Application
application out
//write to System.out
System.out.println(java class);
Operating System
application
out
out
FileOutputStream fos = new FileOutputStream(temp.log); PrintStream ps = new PrintStream(fos); System.setOut(ps); //write to System.out
System.out.println(java class);
Operating System
HD
Example
If the user gives a filename at the command prompt, then the application will redirect output to that file, and also to the console if the user does not give a filename, the application will write only to the console instead Eg: RedirectOutput.java of directing data to the file
Streams Heirarchy
Reader
BufferedReader StringReader
PipedReader All these streams handle chars CharArrayReader InputStreamReader FileReader FilterReader PushbackReader
AbstractClass
Public class
extends
Streams Heirarchy
Writer
BufferedWriter StringWriter PipedWriter FilterWriter PrintWriter
AbstractClass
Public class
extends
RandomAccessFile
Implements DataOut and DataInput It Supports both Reading and writing to a file Constructors: RandomAccessFile(File file, String mode) RandomAccessFile(String name, String mode) The mode argument must either be equal to "r" or "rw", indicating that the file is to be opened for input only or for both input and output, respectively.
RandomAccessFile...
Methods:
long getFilePointer() Returns the current offset in this file.
long length() Returns the length of this file. void seek(long pos) Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
Example
E.g TextIOTest.java ( Writer and RandomAccessFile )
Object Serialization
Converting the state of an object into a serial information (binary / bytes). Uses
Information can be sent over the network to be reconstructed at the other end (rmi) stored in a hard disk as a file, and the object state can be reconstructed much after the object has been removed from memory (i.e persistence)
Example
Write a program to store a string followed by a vector that stores james bond, 007, last line into a file objdata.txt (this example shows serializing the String object and the Vector object) Write a second program to read the file objdata.txt, and display the contents on the console
Example
Consider the Point class
make it Serializable (i.e implements the Serializable interface)
Write another class file SerialPoint.java to store the Point information to a file Read the information from the file and Eg: Point.java Eg:SerialPoint.java display values stored in point object from file
Example
Write some String after serializing the object , read the info stored after de-serializing in a separate variable (initially set to null)
Eg: SerialNewPoint.java
Eg: NewPoint.java
File Channel
A channel for reading, writing, mapping, and manipulating a file. This Slid concentrates on file locking mechanisms. FileChannel.lock() Acquires an exclusive lock on this channel's file.
FileChannel.lock(long position, long size, boolean shared) Acquires a lock on the given region of this channel's file. The above methods return a FileLock Object.
Method : FileLock.release()
FileLockDemo.java
Exercise (contd)
16. A need to persist the data has now arisen as the client observes that the development team is either getting the data from the console or is having it stored as string attributes in the programs. The client wishes that the data should be persisted and reused by any other programs, as well. Hence, store the data in the Collection into a file. Implement methods to read/write the data to/from the given file. The access methods should be synchronized
Exercise (contd)
Apart from persisting data, the input and output operations should not be through the console. Appropriate GUI should be designed to enter the data and show the computed results. Write the required GUI programs which address the functionality of the programs written earlier, using the console for the input/output.