Escolar Documentos
Profissional Documentos
Cultura Documentos
- When you write data to a stream as a series of bytes, that is binary data, it is
written to the stream exactly as it appears in memory. No transformation of
the data takes place. Numerical values are just written as a series of bytes.
- Character streams are used for storing and retrieving text. You can also use
character streams to read a text file not written by a java program.
- Unicode uses 16 bits to represent each character. If the high-order 9 bits are
all zeros, then the encoding is simply standard ASCII, otherwise the bits
represents a character that is not represented in 7-bit ASCII. Java’s char
datatype uses Unicode Encoding.
- Streams are powerful because they abstract away the details of the
communication path from input and output operations. This allows all I/O
to be performed using a common set of methods.
- File class represents the name of a file or directory that might exist on the
hose machine’s file system.
String getAbsolutePath() – This returns the absolute and not the relative path
of file or directory.
String getName()
String getParent() – This returns the name of the directory that contains the
File.
Boolean isDirectory()
Boolean isFile()
String [] list() – This returns an array containing the name of files and
directories within the File (which should be a directory).
Boolean canRead()
Boolean canWrite()
long length()
Boolean mkdir(File f)
import java.awt.*
import java.io.File
System.exit(0);
}
Lister(File f)
{
setSize(300,400);
ta = new TextArea();
ta.setFont(new Font(“Monospaced”, Font.PLAIN, 14));
add(BorderLayout.Center,ta);
recurse(f,0);
}
// recursively list the contents of a direfile, Indent _ 5 space for each level of
depth.
// Indent
ta.append(“ “);
if (child.isDirectory())
recurse(child, depth+1)
// Recurse if dir
}
}
}
FileDemo
FileSplitter1
FileLister
DirList
FilenameFilter Interface
- If we want to limit the number of files returned by the list () method to include
only those files that match a certain filename or filter, we have to implement
this interface.
- This interface has only one method accept () which is called once for each
file in the list.
- The accept method will return true for files in the directory specified by d that
should be included in the list and returns false for files that should be
excluded.
- For using this method, we have to use the overloaded version of list () that is
See TestFF
RandomAccessFile Class
- With a RamdomAccessFile, you can seek a desired position within a file and
then read or write a desired amount of data. The RamdomAccessFile
provides method that support seeking, reading and writing
Constructors
The ‘rw” form of constructor is useful when you want to open some of the
methods of the File class before opening a RAF, so that a instance of File is
in hand when calling the RAF constructor.
After a random Access file is created, you can seek to any byte position within
the file and then read or write. Pre java systems have supported this seeing to a
position relative to the beginning of the file, end of the file or the current position
of the file. The methods
- void seek( long position) thro – This sets the current position within the
file in bytes. Subsequent reading and writing will take place at this
position. Files start at position 0.
1. int read() - this returns the next byte from the file or –1 is end of file
2. int read(byte d[]) – attempts to read enough bytes t fill array d[]
3. int read(byte d[], int o, int n) – attempts to read n number of bytes into
array d[] starting at o.
Streams:
a) Low Level InputStream reads bytes from an input device and returns bytes
to its callers.
b) High Level Filter Input Streams read bytes from a low level input stream or
from another filter input stream and returns general format data to its
caller.
a) int read() – returns the integer representation of the next available byte
of input. –1 is the end of file is encountered.
b) int read (byte b[]) – this will read the bytes in the array.
c) int read(byte b[], int o, int no) – this will read no number of bytes
starting at 0.
a) FileInputStream
b) ByteArrayInputStream
c) SequenceInputStream
FileInputStream
- This class will enable us to create a IS that you can use to read bytes
from a file.
FIS(String filename);
FIS(File f);
- Either of this will throw a checked exception and hence will have to be
put in a try / catch block or the main method will have to throw this
FileNotFoundException.
FileOutputStream
ByteArrayInputStream
- BAIS implements both mark () and reset (). However if mark () has not
been called, then reset () sets the stream pointer to the start of the
stream.
ByteArrayOutputStream
SequenceInputStream
- In the case of the first constructor, the class reads requests from the first
IS until it runs out and then switches to the other and so on.
- In the case of Enumeration, it will continue through all the IS until the end
of the last one is reached.
HighLevelStreams
a) BufferedInputStream
b) DataInputStream
c) PushbackInputStream
- The High Level Streams take Low Level streams always as the
parameter in the constructors.
- The buffered streams allow you to attach a memory buffer to the IO. This
buffer allows java to do IO operations on more than one byte at a time,
hence increasing performance.
PushbackInputStream
DataInputStream
- A data input stream lets an application read primitive Java data types
from an underlying input stream in a machine-independent way. An
application uses a data output stream to write data that can later be read
by a data input stream.
- The constructor for a DIS require InputStream as its parameter
readBoolean
readByte - and so on
Example
try{
dis.close()
fis.clost()
catch (Exception)
-
-
- While the Byte Stream provides all the functionality, they cannot work
directly with Unicode characters.
import java.lang.System;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.System;
import java.io.PushbackInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.System;
import java.io.LineNumberInputStream;
import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.lang.System;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.System;
import java.io.RandomAccessFile;
import java.io.IOException;
Object Persistence
Serialization
An object records itself by writing out the values that describe its state. This
process is know as serialisation because the object is represented by an ordered
series of bytes. Java provides classes that write objects to streams and restore
objects from streams.
The main task of serialization is to write out the values of an object’s instance
variables. If a variable is a reference to another object, the referenced object
must also be serialised. Serialization may involve serializing a complex tree
structure that consists of the original object, the object’s object and so on.
Not all classes are capable of being serialized. Only objects that implement the
Serializable or Externalizable interfaces may successfully be serialized. Both the
classes are in java.io package. A Serializable object can be serialized by another
object, which is in practice is a type of output stream. An Externalizable object
must be capable of writing its own state, rather than letting the work be done by
another object.
The Serializable Interface
This interface does not have any methods. When a class declares that it
implements Serializable, it is declaring that it participates in the serialization
protocol. When an object is Serializable and the object’s state is written to a
stream, the stream must contain enough information to restore the object. This
must hold true even if the class being restored has been updated to a more
recent (but compatible) version. One can serialize any class as long as the class
meets the following criteria:
If a Serializable class has variables that should not be serialized those variables
must be marked with the transient keyword. The serialization process will ignore
any variables marked as transient. In general, references to AWT classes that
rely on System peers should be marked as transient. Many things - like static
data, open file handles, socket connections and threads will not be Serializable
since they represent items that are very JVM specific.
Externalizable Interface
The Externalizable interface identifies objects that can be saved to a stream but
are responsible for their own states. When an exter object is written to a stream,
the stream is responsible for storing the name of the object’s class, the object
must write its own data. An exter class must adhere to this interface by providing
a writeExternal () for storing its state during serialization and readExternal () for
restoring its state during deserialization.
Objects that can serialize other objects implement the ObjectOutput Interface
from the io package. This interface is implemented by output stream class and
extends the DataOutput class.
The DataOutput interface support writing of primitive data types and these
methods are used for writing out an object’s primitive instance variables.
Serializable objects are represented as streams of bytes, rather than as
characters. Therefore they are handled by streams rather than by character
oriented streams.
The next step is to create an object output stream and chain it to the fos
The object output stream automatically writes a header into the streams; the
header contains a magic number and a version. This data is written automatically
with the writeStreamHeader () when the object output stream is created.
After writing the header; the oos will write the bit representation of an object to
the oos using the writeObject method. Note: Without calling the reset () of the
java.io.Serializable you cannot use the same stream to write the same object
reference twice.
Deserialization
The obj i.s class reads serialized object data. By using the methods of this class,
a program can restore a serialised object along with the entire tree of objects
referred to by the primary object from the stream. Primitive data type may also be
read from an obj i.s.
Object Validation
Once an object has been retrieved from a stream, it must be validated so it can
become a full fledged object and can be used by a the program that deserialized
it. The validateObject() method is called when a complete graph of objects has
been retrieved from a stream. If the primary object cannot be made valid, the
validation will stop and an exception will be thrown.
Serialization can involve storing an object’s data on a disk file or transmitting the
data across the network. In both cases, there is a potential security problem
because the data is located outside the JVM – beyond the reach of java’s
security mechanism.
The following example reads a string from the keyboard and prints it
import java.io.*;
class Input
{
public static void main (String arg[]) throws IOException
{
System.out,print (“Enter a String “);
BufferedReader br =new BufferedReader ( new InputStreamReader
(System.in)));
System.out.println (“The String you have entered is: “+br.readLine));
}
}
By using streams, you can create java programs that read data form a
source, process the data and write the results to a destination.
import java.io.*;
class CopyFile
{
public static void main (String arg[])
{
InputStream m_input = null;
OutputStream m_output = null;
try
{
System.out.println(“Opening Files..”)’
byte data;
System.out.println(“File copied”);
}
catch (Exception e)
{
System.out.println(“IO Error” + e.getMessage ());
}
System.exit (0);
}
}