Download NEW JAVA UNIT 5 - E

Document related concepts
no text concepts found
Transcript
JAVA PROGRAMMING
SUBJECT
CLASS
UNIT
SEMESTER
STAFF
NASC –CS&IT
: JAVA PROGRAMMING
: III BSC CS
: V
: 6
: I.GOBI
UNIT-V
Managing Input / Output Files in Java : Concepts of Streams- Stream Classes – Byte
Stream classes – Character stream classes – Using streams – I/O Classes – File Class – I/O
exceptions – Creation of files – Reading / Writing characters, Byte-Handling Primitive data
Types – Random Access Files.
CONCEPTS OF INPUT/OUTPUT STREAMS
OVERVIEW OF STREAMS
Stream:
Flow of anything from one point to another point sequentially is called Stream.
During program execution, the input flows from file or string or keyboard or mouse to
program and output data flows from program to result or screen or memory etc. This type
of data flows from input device to program and from program to output device is called
data streams or simply streams. Stream is defined as a path along which data flows.
Java has two types of streams called input stream and output stream.
- Flow of data from data source (file input) to program, is called Input Stream.
- Flow of data from program to screen or memory (designation file) called Output
Stream.
FLOW FUNCTION:
Input Stream
FILE
PROGRAM
Output Stream
JAVA PROGRAMMING
NASC –CS&IT
As the data flows the read & write process occurs continuously.
STREAM ADVANTAGES
- Streams help the user to build dynamic codes to match their type of data transfer.
- It simplifies the complex of I/O operations.
- The available stream classes functions properly even though new stream classes are
invented in future.
- The Stream classes works well from one file system based on one stream to another
type of file system with another stream.
- It helps to serialize objects.
STREAM CLASS
Stream classes are present in the java.io package. These classes provide facilities to
process
all types of data. Stream classes are divided into two groups based on the type of data.
1. Byte stream classes // Using for IO operation in bytes
2. Character stream classes // using for IO operation in characters.
A group of classes are used to perform IO operations using various types of devices. The
source and designation of data may be memory, a file of a pipe (communication between
threads)
BYTES VS. CHARACTERS
BYTE STREAM:
Byte stream classes provide facilities to process I/O in bytes. A byte stream can be used
with
any type of data including binary data. Since the streams are unidirectional, they can
transmit data bytes in one direction only.
Therefore there are two abstract classes namely Input Stream and Output Stream which
JAVA PROGRAMMING
NASC –CS&IT
are used to read and write process. These abstract classes contain several subclasses to
handle different I/O devices.
1. Input Stream
Input stream is an abstract class and it is used to stream input data in bytes. It is used for
reading the data such as byte and array from an input. An input may be from a file, string or
memory. This class contains number of methods used to process input. Here errors may
occur, hence it throws IO Exception.
Class methods:
int available() - it gives the number of bytes of input currently available for
reading.
void close() - it is used to close the input source.
int read() - it is used to read a byte from Input Stream.
int read(byte b[])- it is used to read an array of bytes into byte b array.
FILTERS:
Filtering is a process of combining the data bytes into meaningful primitive data type units
and monitoring line numbers.
The dataInputStream class extends from FilterInputStream class and implements from
DataInput interface. It has many methods, they are.
1. readInt() - read integer value from given input.
2. readLong() - read long value from given input.
3. readFloat() - same as int, long.
4. readLine() - read a line from given input.
5. readChar() - read character value from given input.
JAVA PROGRAMMING
NASC –CS&IT
6. readBoolean() - read true or false from given Boolean value
Hierarchical structure of Input Stream:
2. OUTPUT STREAM:
Output stream is an abstract class and it is used to stream output data in bytes. It has
many
methods used to process output. Here error may occur in the class/method, so it throws I/O
Exception. Methods are given below.
void close() - it is used to close the stream.
void flush() - it is used to clear the output buffers.
void writte(int b) - it is used to write a single byte to an output
stream.
void write(byte b[]) - it is used to write a buffer array in byte b to an
output stream.
void write(byte b[], int I, int j)-it is used to write ‘j’ bytes form buffer array ’b’ starting
from’ I’ byte.
Hierarchical structure of Output Stream:
JAVA PROGRAMMING
Example Program
import java.io.*;
class ioexample
{
public static void main(String[] args)
{
try {
File ip = new File("input.txt");
File op = new File("output.txt");
FileInputStream fis = new
FileInputStream(ip);
FileOutputStream fos = new
FileOutputStream(op);
int i;
while ((i = fis.read()) != -1)
{
fos.write(i);
}
fis.close();
fos.close();
}
catch (FileNotFoundException fnfe)
{
System.err.println("FileStreamsTest: " +
fnfe);
}
catch (IOException ioe)
{
System.err.println("FileStreamsTest: " + ioe);
} }}
NASC –CS&IT
JAVA PROGRAMMING
NASC –CS&IT
The above program handles the input stream and output stream, when input given is in the
form of input.txt file and the output creates new file named as output.txt file.
Input file is:
Compile the file:
CHARACTER STREAM CLASSES:
Character stream classes are used to process I/O 16 bit Unicode characters. There
are two
types of character stream classes.
JAVA PROGRAMMING
NASC –CS&IT
They are:
Reader class
Writer class
Reader class:
Reader is an abstract class which is used to stream character input data. This class contains
number of methods to do input operations. Error may occur in the class, so it throws
IOException.
This class has many methods, they are.
abstract void close() - it is used to close input source.
int read() - it is used to return an integer representation of the next
available character from the invoking input stream.
int read(char b[]) - it is used to read up to length of character into the
buffer array b. then it returns the actual number of characters that were successfully
read.
abstract int read(char b[], int I, int j)- it is used to ream j characters into buffer b
starting from I index.
Boolean read() - this method returns true next input is not waiting else false.
Example program
import java.io.*;
public class readexample
{
public static void main(String[] args) throws
IOException
JAVA PROGRAMMING
NASC –CS&IT
{
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter your text Here : ");
String st = in.readLine();
System.out.println("Entered Text is: "+st);
}
}
Output
WRITER CLASS
Writer is an abstract class and it is used to stream character output data. This class
contains number of methods. If error occurs it throws I/O Exception.
• abstract void close() - it is used to close the output stream.
• abstract void flush() - it is used to clear the output buffers.
• void write(int b) - it is used to write a buffer array of character to
an output stream.
• void write(byte b) - it is used to write a buffer array of characters to
an output stream.
• Void write(byte b[], int I, int j)- it is used to write ‘j’ characters from buffer’ b’
starting from ‘i’ index character.
JAVA PROGRAMMING
import java.io.*;
public class writeexample
{
public static void main(String[] args) throws
IOException
{
File file=new File("write.txt");
FileOutputStream fop=new FileOutputStream(file);
if(file.exists())
{
String st="Writer Class:Writer is an abstract class
and it is used to stream character output data.";
fop.write(st.getBytes());
fop.flush();
fop.close();
System.out.println("The file has been written
and created file name is write.txt ");
}
else
System.out.println("This file is not exist");
}}
COMPILE
NASC –CS&IT
JAVA PROGRAMMING
NASC –CS&IT
File created: “write.txt”
1.3 Converting Byte Streams to Character Streams
Java. Lang Package provides the conversion functionality to convert byte value to String,
character or Hexadecimal values.
import java.io.*;
import java.lang.*;
public class convertbyte
{
public static void main(String[] args) throws
IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Valid Number");
byte b =(byte)4;
String str = br.readLine();
int i =Integer.parseInt(str);
JAVA PROGRAMMING
String st = Integer.toHexString(i);
System.out.println("Converted Byte to
Charecter/String/HexaDecimal:=" + st);
}
}
CONVERT CHARACTER TO BYTE
import java.io.*;
import java.lang.*;
public class convertexample
{
public static void main(String[] args) throws
IOException
{
BufferedReader br = new BufferedReader(new
NASC –CS&IT
JAVA PROGRAMMING
InputStreamReader(System.in));
System.out.println("Enter your charecters");
String st = br.readLine();
char c = st.charAt(2);
byte b = (byte)c;
System.out.println("Converted character value to Byte
Value is:=" + b); }
}
1.4 File Object
import java.io.*;
public class fileexample
{
public static void main(String[] args) throws
IOException
{
File f=new File("file.txt");
if(!f.exists())
{
f.createNewFile();
NASC –CS&IT
JAVA PROGRAMMING
NASC –CS&IT
System.out.println("New File Has been created
"file.txt" using File");
}
}
}
Created new file named as file.txt
1.5 Binary Input and Output
Byte Stream is used to provide binary Input and Output. It is 8 bit and the streams
communicate between the source and the designation file.
The input stream is used to read a sequence of bytes and the output stream is used to write
a sequence of bytes.
1. All streams are derived from either input or output abstract classes.
2. All methods throw an IOException in both I/O classes.
3. Reader and Writer classes are available.
INPUT STREAM
This class is an abstract class & it is used to read input from one designation.
JAVA PROGRAMMING
NASC –CS&IT
Methods are used to read inputs:
public abstract int read() throws IOException
It is used to read the byte data from the input designation. Its return type is int and its
range
is 0 to 255. The read() method returns a value. This method runs until stream is detected or
an exception is thrown.
public int read( byte[] b ) throws IOException
This method is used to read the array b upto its length. Return byte values or -1 returned.
public int available() throws IOException
returns the available bytes.
public void close() throws IOException
Method used to close the Input stream.
Ex:
import java.io.*;
class inputexample
{
public static void main(String args[])
throws IOException
{int i;
InputStream is=new FileInputStream("inputexample.java");
System.out.println(" total bytes"+ (i=is.available()));
int n=i/40;
System.out.println("First" +n+"bytes");
for(int a=0; a<n; a++)
JAVA PROGRAMMING
NASC –CS&IT
{
System.out.println((char) is.read());
}System.out.println("available"+is.available());
System.out.println("reading next"+n);
byte b[]=new byte[n];
if(is.read(b) !=n)
{
System.out.println("could not readb"+n);
}}}
OUTPUT STREAM
This output stream class is also an abstract class. Methods are given below.
public abstract void write( int b ) throws IOException
It is used to write ‘b’ as an output of the stream. Lower 8 bit and high 24 bits are lost.
public void write( byte[] b ) throws IOException
This method writes the array of byte’ b’ to the output stream.
public int flush() throws IOException
flushed in a bytes, which is in buffer out of the stream.
public void close() throws IOException
Method is closed to the output stream
This output stream has two subclasses named as reader and writer. The read() and write()
methods waits until the complete process get finished.
Eg: input or output.
JAVA PROGRAMMING
import java.io.*;
class outputexample
{
public static void main(String arg[])throws IOException
{
String s="ICT Academy \n"+"Java COurse";
byte b[]=s.getBytes();
OutputStream os=new FileOutputStream("ex.txt");
for(int a=0; a<b.length; a+=2)
{
os.write(b[a]);
}
os.close();
OutputStream os1=new FileOutputStream("ex1.txt");
os1.write(b);
os1.close();
}
}
File has been created using OutputStream class:
CLASS FILE
NASC –CS&IT
JAVA PROGRAMMING
NASC –CS&IT
java.io
Class File
java.lang.Object
java.io.File
All Implemented Interfaces:
Comparable, Serializable
public class File
extends Object
implements Serializable, Comparable
An abstract representation of file and directory pathnames.
User interfaces and operating systems use system-dependent pathname strings to name files and
directories. This class presents an abstract, system-independent view of hierarchical pathnames.
An abstract pathname has two components:
1. An optional system-dependent prefix string, such as a disk-drive specifier, "/" for the UNIX root
directory, or "\\" for a Microsoft Windows UNC pathname, and
2. A sequence of zero or more string names.
Each name in an abstract pathname except for the last denotes a directory; the last name may denote
either a directory or a file. The empty abstract pathname has no prefix and an empty name sequence.
The conversion of a pathname string to or from an abstract pathname is inherently systemdependent. When an abstract pathname is converted into a pathname string, each name is
separated from the next by a single copy of the default separator character. The default nameseparator character is defined by the system property file.separator, and is made available in
the public static fields separator and separatorChar of this class. When a pathname string is
converted into an abstract pathname, the names within it may be separated by the default nameseparator character or by any other name-separator character that is supported by the underlying
system.
A pathname, whether abstract or in string form, may be either absolute or relative. An absolute
pathname is complete in that no other information is required in order to locate the file that it
denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from
some other pathname. By default the classes in the java.io package always resolve relative
JAVA PROGRAMMING
NASC –CS&IT
pathnames against the current user directory. This directory is named by the system property
user.dir, and is typically the directory in which the Java virtual machine was invoked.
The prefix concept is used to handle root directories on UNIX platforms, and drive specifiers,
root directories and UNC pathnames on Microsoft Windows platforms, as follows:


For UNIX platforms, the prefix of an absolute pathname is always "/". Relative pathnames have
no prefix. The abstract pathname denoting the root directory has the prefix "/" and an empty name
sequence.
For Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier
consists of the drive letter followed by ":" and possibly followed by "\" if the pathname is
absolute. The prefix of a UNC pathname is "\\"; the hostname and the share name are the first two
names in the name sequence. A relative pathname that does not specify a drive has no prefix.
Instances of the File class are immutable; that is, once created, the abstract pathname
represented by a File object will never change.
Field Summary
static String pathSeparator
The system-dependent path-separator character, represented as a string for
convenience.
static char pathSeparatorChar
The system-dependent path-separator character.
static String separator
The system-dependent default name-separator character, represented as a string for
convenience.
static char separatorChar
The system-dependent default name-separator character.
Constructor Summary
File(File parent, String child)
Creates a new File instance from a parent abstract pathname and a child pathname string.
JAVA PROGRAMMING
NASC –CS&IT
File(String pathname)
Creates a new File instance by converting the given pathname string into an abstract pathname.
File(String parent, String child)
Creates a new File instance from a parent pathname string and a child pathname string.
File(URI uri)
Creates a new File instance by converting the given file: URI into an abstract pathname.
Method Summary
boolean canRead()
Tests whether the application can read the file denoted by this abstract pathname.
boolean canWrite()
Tests whether the application can modify to the file denoted by this abstract pathname.
int compareTo(File pathname)
Compares two abstract pathnames lexicographically.
int compareTo(Object o)
Compares this abstract pathname to another object.
boolean createNewFile()
Atomically creates a new, empty file named by this abstract pathname if and only if a
file with this name does not yet exist.
static File createTempFile(String prefix, String suffix)
Creates an empty file in the default temporary-file directory, using the given prefix and
suffix to generate its name.
static File createTempFile(String prefix, String suffix, File directory)
Creates a new empty file in the specified directory, using the given prefix and suffix
strings to generate its name.
boolean delete()
Deletes the file or directory denoted by this abstract pathname.
JAVA PROGRAMMING
NASC –CS&IT
void deleteOnExit()
Requests that the file or directory denoted by this abstract pathname be deleted when the
virtual machine terminates.
boolean equals(Object obj)
Tests this abstract pathname for equality with the given object.
boolean exists()
Tests whether the file or directory denoted by this abstract pathname exists.
File getAbsoluteFile()
Returns the absolute form of this abstract pathname.
String getAbsolutePath()
Returns the absolute pathname string of this abstract pathname.
File getCanonicalFile()
Returns the canonical form of this abstract pathname.
String getCanonicalPath()
Returns the canonical pathname string of this abstract pathname.
String getName()
Returns the name of the file or directory denoted by this abstract pathname.
String getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname
does not name a parent directory.
File getParentFile()
Returns the abstract pathname of this abstract pathname's parent, or null if this pathname
does not name a parent directory.
String getPath()
Converts this abstract pathname into a pathname string.
int hashCode()
Computes a hash code for this abstract pathname.
boolean isAbsolute()
Tests whether this abstract pathname is absolute.
JAVA PROGRAMMING
NASC –CS&IT
boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory.
boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal file.
boolean isHidden()
Tests whether the file named by this abstract pathname is a hidden file.
long lastModified()
Returns the time that the file denoted by this abstract pathname was last modified.
long length()
Returns the length of the file denoted by this abstract pathname.
String[] list()
Returns an array of strings naming the files and directories in the directory denoted by
this abstract pathname.
String[] list(FilenameFilter filter)
Returns an array of strings naming the files and directories in the directory denoted by
this abstract pathname that satisfy the specified filter.
File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by
this abstract pathname.
File[] listFiles(FileFilter filter)
Returns an array of abstract pathnames denoting the files and directories in the directory
denoted by this abstract pathname that satisfy the specified filter.
File[] listFiles(FilenameFilter filter)
Returns an array of abstract pathnames denoting the files and directories in the directory
denoted by this abstract pathname that satisfy the specified filter.
static File[] listRoots()
List the available filesystem roots.
boolean mkdir()
Creates the directory named by this abstract pathname.
JAVA PROGRAMMING
NASC –CS&IT
boolean mkdirs()
Creates the directory named by this abstract pathname, including any necessary but
nonexistent parent directories.
boolean renameTo(File dest)
Renames the file denoted by this abstract pathname.
boolean setLastModified(long time)
Sets the last-modified time of the file or directory named by this abstract pathname.
boolean setReadOnly()
Marks the file or directory named by this abstract pathname so that only read operations
are allowed.
String toString()
Returns the pathname string of this abstract pathname.
URI toURI()
Constructs a file: URI that represents this abstract pathname.
URL toURL()
Converts this abstract pathname into a file: URL.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Field Detail
separatorChar
public static final char separatorChar
The system-dependent default name-separator character. This field is initialized to contain the
first character of the value of the system property file.separator. On UNIX systems the value of
this field is '/'; on Microsoft Windows systems it is '\'.
See Also:
JAVA PROGRAMMING
NASC –CS&IT
System.getProperty(java.lang.String)
separator
public static final String separator
The system-dependent default name-separator character, represented as a string for convenience.
This string contains a single character, namely separatorChar.
pathSeparatorChar
public static final char pathSeparatorChar
The system-dependent path-separator character. This field is initialized to contain the first
character of the value of the system property path.separator. This character is used to separate
filenames in a sequence of files given as a path list. On UNIX systems, this character is ':'; on
Microsoft Windows systems it is ';'.
See Also:
System.getProperty(java.lang.String)
pathSeparator
public static final String pathSeparator
The system-dependent path-separator character, represented as a string for convenience. This
string contains a single character, namely pathSeparatorChar.
Constructor Detail
File
public File(String pathname)
Creates a new File instance by converting the given pathname string into an abstract pathname. If
the given string is the empty string, then the result is the empty abstract pathname.
Parameters:
pathname - A pathname string
JAVA PROGRAMMING
NASC –CS&IT
Throws:
NullPointerException - If the pathname argument is null
File
public File(String parent,
String child)
Creates a new File instance from a parent pathname string and a child pathname string.
If parent is null then the new File instance is created as if by invoking the singleargument File constructor on the given child pathname string.
Otherwise the parent pathname string is taken to denote a directory, and the child
pathname string is taken to denote either a directory or a file. If the child pathname
string is absolute then it is converted into a relative pathname in a system-dependent way.
If parent is the empty string then the new File instance is created by converting child
into an abstract pathname and resolving the result against a system-dependent default
directory. Otherwise each pathname string is converted into an abstract pathname and the
child abstract pathname is resolved against the parent.
Parameters:
parent - The parent pathname string
child - The child pathname string
Throws:
NullPointerException - If child is null
File
public File(File parent,
String child)
Creates a new File instance from a parent abstract pathname and a child pathname string.
If parent is null then the new File instance is created as if by invoking the singleargument File constructor on the given child pathname string.
Otherwise the parent abstract pathname is taken to denote a directory, and the child
pathname string is taken to denote either a directory or a file. If the child pathname
JAVA PROGRAMMING
NASC –CS&IT
string is absolute then it is converted into a relative pathname in a system-dependent way.
If parent is the empty abstract pathname then the new File instance is created by
converting child into an abstract pathname and resolving the result against a systemdependent default directory. Otherwise each pathname string is converted into an abstract
pathname and the child abstract pathname is resolved against the parent.
Parameters:
parent - The parent abstract pathname
child - The child pathname string
Throws:
NullPointerException - If child is null
File
public File(URI uri)
Creates a new File instance by converting the given file: URI into an abstract pathname.
The exact form of a file: URI is system-dependent, hence the transformation performed
by this constructor is also system-dependent.
For a given abstract pathname f it is guaranteed that
new File( f.toURI()).equals( f.getAbsoluteFile())
so long as the original abstract pathname, the URI, and the new abstract pathname are all created
in (possibly different invocations of) the same Java virtual machine. This relationship typically
does not hold, however, when a file: URI that is created in a virtual machine on one operating
system is converted into an abstract pathname in a virtual machine on a different operating
system.
Parameters:
uri - An absolute, hierarchical URI with a scheme equal to "file", a non-empty path component,
and undefined authority, query, and fragment components
Throws:
NullPointerException - If uri is null
IllegalArgumentException - If the preconditions on the parameter do not hold
JAVA PROGRAMMING
NASC –CS&IT
Since:
1.4
See Also:
toURI(), URI
Method Detail
getName
public String getName()
Returns the name of the file or directory denoted by this abstract pathname. This is just the last
name in the pathname's name sequence. If the pathname's name sequence is empty, then the
empty string is returned.
Returns:
The name of the file or directory denoted by this abstract pathname, or the empty string if this
pathname's name sequence is empty
getParent
public String getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not
name a parent directory.
The parent of an abstract pathname consists of the pathname's prefix, if any, and each
name in the pathname's name sequence except for the last. If the name sequence is empty
then the pathname does not name a parent directory.
Returns:
The pathname string of the parent directory named by this abstract pathname, or null if this
pathname does not name a parent
getParentFile
JAVA PROGRAMMING
NASC –CS&IT
public File getParentFile()
Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not
name a parent directory.
The parent of an abstract pathname consists of the pathname's prefix, if any, and each
name in the pathname's name sequence except for the last. If the name sequence is empty
then the pathname does not name a parent directory.
Returns:
The abstract pathname of the parent directory named by this abstract pathname, or null if this
pathname does not name a parent
Since:
1.2
getPath
public String getPath()
Converts this abstract pathname into a pathname string. The resulting string uses the default nameseparator character to separate the names in the name sequence.
Returns:
The string form of this abstract pathname
isAbsolute
public boolean isAbsolute()
Tests whether this abstract pathname is absolute. The definition of absolute pathname is system
dependent. On UNIX systems, a pathname is absolute if its prefix is "/". On Microsoft Windows
systems, a pathname is absolute if its prefix is a drive specifier followed by "\\", or if its prefix is
"\\".
Returns:
true if this abstract pathname is absolute, false otherwise
getAbsolutePath
JAVA PROGRAMMING
NASC –CS&IT
public String getAbsolutePath()
Returns the absolute pathname string of this abstract pathname.
If this abstract pathname is already absolute, then the pathname string is simply returned
as if by the getPath() method. If this abstract pathname is the empty abstract pathname
then the pathname string of the current user directory, which is named by the system
property user.dir, is returned. Otherwise this pathname is resolved in a systemdependent way. On UNIX systems, a relative pathname is made absolute by resolving it
against the current user directory. On Microsoft Windows systems, a relative pathname is
made absolute by resolving it against the current directory of the drive named by the
pathname, if any; if not, it is resolved against the current user directory.
Returns:
The absolute pathname string denoting the same file or directory as this abstract pathname
Throws:
SecurityException - If a required system property value cannot be accessed.
See Also:
isAbsolute()
getAbsoluteFile
public File getAbsoluteFile()
Returns the absolute form of this abstract pathname. Equivalent to
new File(this.getAbsolutePath()()).
Returns:
The absolute abstract pathname denoting the same file or directory as this abstract pathname
Throws:
SecurityException - If a required system property value cannot be accessed.
Since:
1.2
getCanonicalPath
JAVA PROGRAMMING
NASC –CS&IT
public String getCanonicalPath()
throws IOException
Returns the canonical pathname string of this abstract pathname.
A canonical pathname is both absolute and unique. The precise definition of canonical
form is system-dependent. This method first converts this pathname to absolute form if
necessary, as if by invoking the getAbsolutePath() method, and then maps it to its
unique form in a system-dependent way. This typically involves removing redundant
names such as "." and ".." from the pathname, resolving symbolic links (on UNIX
platforms), and converting drive letters to a standard case (on Microsoft Windows
platforms).
Every pathname that denotes an existing file or directory has a unique canonical form.
Every pathname that denotes a nonexistent file or directory also has a unique canonical
form. The canonical form of the pathname of a nonexistent file or directory may be
different from the canonical form of the same pathname after the file or directory is
created. Similarly, the canonical form of the pathname of an existing file or directory may
be different from the canonical form of the same pathname after the file or directory is
deleted.
Returns:
The canonical pathname string denoting the same file or directory as this abstract pathname
Throws:
IOException - If an I/O error occurs, which is possible because the construction of the canonical
pathname may require filesystem queries
SecurityException - If a required system property value cannot be accessed.
Since:
JDK1.1
getCanonicalFile
public File getCanonicalFile()
throws IOException
Returns the canonical form of this abstract pathname. Equivalent to
new File(this.getCanonicalPath()()).
Returns:
The canonical pathname string denoting the same file or directory as this abstract pathname
Throws:
JAVA PROGRAMMING
NASC –CS&IT
IOException - If an I/O error occurs, which is possible because the construction of the canonical
pathname may require filesystem queries
SecurityException - If a required system property value cannot be accessed.
Since:
1.2
toURL
public URL toURL()
throws MalformedURLException
Converts this abstract pathname into a file: URL. The exact form of the URL is systemdependent. If it can be determined that the file denoted by this abstract pathname is a directory,
then the resulting URL will end with a slash.
Usage note: This method does not automatically escape characters that are illegal in
URLs. It is recommended that new code convert an abstract pathname into a URL by first
converting it into a URI, via the toURI method, and then converting the URI into a URL
via the URI.toURL method.
Returns:
A URL object representing the equivalent file URL
Throws:
MalformedURLException - If the path cannot be parsed as a URL
Since:
1.2
See Also:
toURI(), URI, URI.toURL(), URL
toURI
public URI toURI()
Constructs a file: URI that represents this abstract pathname.
The exact form of the URI is system-dependent. If it can be determined that the file
denoted by this abstract pathname is a directory, then the resulting URI will end with a
slash.
JAVA PROGRAMMING
NASC –CS&IT
For a given abstract pathname f, it is guaranteed that
new File( f.toURI()).equals( f.getAbsoluteFile())
so long as the original abstract pathname, the URI, and the new abstract pathname are all created
in (possibly different invocations of) the same Java virtual machine. Due to the system-dependent
nature of abstract pathnames, however, this relationship typically does not hold when a file: URI
that is created in a virtual machine on one operating system is converted into an abstract
pathname in a virtual machine on a different operating system.
Returns:
An absolute, hierarchical URI with a scheme equal to "file", a path representing this abstract
pathname, and undefined authority, query, and fragment components
Since:
1.4
See Also:
File(java.net.URI), URI, URI.toURL()
canRead
public boolean canRead()
Tests whether the application can read the file denoted by this abstract pathname.
Returns:
true if and only if the file specified by this abstract pathname exists and can be read by the
application; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the file
canWrite
public boolean canWrite()
Tests whether the application can modify to the file denoted by this abstract pathname.
Returns:
JAVA PROGRAMMING
NASC –CS&IT
true if and only if the file system actually contains a file denoted by this abstract pathname and
the application is allowed to write to the file; false otherwise.
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method denies write access to the file
exists
public boolean exists()
Tests whether the file or directory denoted by this abstract pathname exists.
Returns:
true if and only if the file or directory denoted by this abstract pathname exists; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the file or directory
isDirectory
public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory.
Returns:
true if and only if the file denoted by this abstract pathname exists and is a directory; false
otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the file
isFile
public boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is
not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file
created by a Java application is guaranteed to be a normal file.
Returns:
JAVA PROGRAMMING
NASC –CS&IT
true if and only if the file denoted by this abstract pathname exists and is a normal file; false
otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the file
isHidden
public boolean isHidden()
Tests whether the file named by this abstract pathname is a hidden file. The exact definition of
hidden is system-dependent. On UNIX systems, a file is considered to be hidden if its name
begins with a period character ('.'). On Microsoft Windows systems, a file is considered to be
hidden if it has been marked as such in the filesystem.
Returns:
true if and only if the file denoted by this abstract pathname is hidden according to the
conventions of the underlying platform
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the file
lastModified
public long lastModified()
Returns the time that the file denoted by this abstract pathname was last modified.
Returns:
A long value representing the time the file was last modified, measured in milliseconds since the
epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the file
length
public long length()
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if
this pathname denotes a directory.
JAVA PROGRAMMING
NASC –CS&IT
Returns:
The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the file
createNewFile
public boolean createNewFile()
throws IOException
Atomically creates a new, empty file named by this abstract pathname if and only if a file with
this name does not yet exist. The check for the existence of the file and the creation of the file if it
does not exist are a single operation that is atomic with respect to all other filesystem activities
that might affect the file.
Note: this method should not be used for file-locking, as the resulting protocol cannot be
made to work reliably. The FileLock facility should be used instead.
Returns:
true if the named file does not exist and was successfully created; false if the named file already
exists
Throws:
IOException - If an I/O error occurred
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method denies write access to the file
delete
public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a
directory, then the directory must be empty in order to be deleted.
Returns:
true if and only if the file or directory is successfully deleted; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String)
method denies delete access to the file
JAVA PROGRAMMING
NASC –CS&IT
deleteOnExit
public void deleteOnExit()
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual
machine terminates. Deletion will be attempted only for normal termination of the virtual
machine, as defined by the Java Language Specification.
Once deletion has been requested, it is not possible to cancel the request. This method
should therefore be used with care.
Note: this method should not be used for file-locking, as the resulting protocol cannot be
made to work reliably. The FileLock facility should be used instead.
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String)
method denies delete access to the file
list
public String[] list()
Returns an array of strings naming the files and directories in the directory denoted by this
abstract pathname.
If this abstract pathname does not denote a directory, then this method returns null.
Otherwise an array of strings is returned, one for each file or directory in the directory.
Names denoting the directory itself and the directory's parent directory are not included
in the result. Each string is a file name rather than a complete path.
There is no guarantee that the name strings in the resulting array will appear in any
specific order; they are not, in particular, guaranteed to appear in alphabetical order.
Returns:
An array of strings naming the files and directories in the directory denoted by this abstract
pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname
does not denote a directory, or if an I/O error occurs.
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the directory
list
JAVA PROGRAMMING
NASC –CS&IT
public String[] list(FilenameFilter filter)
Returns an array of strings naming the files and directories in the directory denoted by this
abstract pathname that satisfy the specified filter. The behavior of this method is the same as that
of the list() method, except that the strings in the returned array must satisfy the filter. If the given
filter is null then all names are accepted. Otherwise, a name satisfies the filter if and only if the
value true results when the FilenameFilter.accept(java.io.File, java.lang.String) method of the filter is
invoked on this abstract pathname and the name of a file or directory in the directory that it
denotes.
Parameters:
filter - A filename filter
Returns:
An array of strings naming the files and directories in the directory denoted by this abstract
pathname that were accepted by the given filter. The array will be empty if the directory is empty
or if no names were accepted by the filter. Returns null if this abstract pathname does not denote a
directory, or if an I/O error occurs.
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the directory
listFiles
public File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract
pathname.
If this abstract pathname does not denote a directory, then this method returns null.
Otherwise an array of File objects is returned, one for each file or directory in the
directory. Pathnames denoting the directory itself and the directory's parent directory are
not included in the result. Each resulting abstract pathname is constructed from this
abstract pathname using the File(File, String) constructor. Therefore if this
pathname is absolute then each resulting pathname is absolute; if this pathname is relative
then each resulting pathname will be relative to the same directory.
There is no guarantee that the name strings in the resulting array will appear in any
specific order; they are not, in particular, guaranteed to appear in alphabetical order.
Returns:
JAVA PROGRAMMING
NASC –CS&IT
An array of abstract pathnames denoting the files and directories in the directory denoted by this
abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract
pathname does not denote a directory, or if an I/O error occurs.
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the directory
listFiles
public File[] listFiles(FilenameFilter filter)
Returns an array of abstract pathnames denoting the files and directories in the directory denoted
by this abstract pathname that satisfy the specified filter. The behavior of this method is the same
as that of the listFiles() method, except that the pathnames in the returned array must satisfy the
filter. If the given filter is null then all pathnames are accepted. Otherwise, a pathname satisfies the
filter if and only if the value true results when the FilenameFilter.accept(java.io.File, java.lang.String)
method of the filter is invoked on this abstract pathname and the name of a file or directory in the
directory that it denotes.
Parameters:
filter - A filename filter
Returns:
An array of abstract pathnames denoting the files and directories in the directory denoted by this
abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract
pathname does not denote a directory, or if an I/O error occurs.
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the directory
listFiles
public File[] listFiles(FileFilter filter)
Returns an array of abstract pathnames denoting the files and directories in the directory denoted
by this abstract pathname that satisfy the specified filter. The behavior of this method is the same
as that of the listFiles() method, except that the pathnames in the returned array must satisfy the
filter. If the given filter is null then all pathnames are accepted. Otherwise, a pathname satisfies the
filter if and only if the value true results when the FileFilter.accept(java.io.File) method of the filter
is invoked on the pathname.
Parameters:
JAVA PROGRAMMING
NASC –CS&IT
filter - A file filter
Returns:
An array of abstract pathnames denoting the files and directories in the directory denoted by this
abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract
pathname does not denote a directory, or if an I/O error occurs.
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String)
method denies read access to the directory
mkdir
public boolean mkdir()
Creates the directory named by this abstract pathname.
Returns:
true if and only if the directory was created; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method does not permit the named directory to be created
mkdirs
public boolean mkdirs()
Creates the directory named by this abstract pathname, including any necessary but nonexistent
parent directories. Note that if this operation fails it may have succeeded in creating some of the
necessary parent directories.
Returns:
true if and only if the directory was created, along with all necessary parent directories; false
otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method does not permit the named directory and all necessary parent directories and to be created
renameTo
JAVA PROGRAMMING
NASC –CS&IT
public boolean renameTo(File dest)
Renames the file denoted by this abstract pathname.
Whether or not this method can move a file from one filesystem to another is platformdependent. The return value should always be checked to make sure that the rename
operation was successful.
Parameters:
dest - The new abstract pathname for the named file
Returns:
true if and only if the renaming succeeded; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method denies write access to either the old or new pathnames
NullPointerException - If parameter dest is null
setLastModified
public boolean setLastModified(long time)
Sets the last-modified time of the file or directory named by this abstract pathname.
All platforms support file-modification times to the nearest second, but some provide
more precision. The argument will be truncated to fit the supported precision. If the
operation succeeds and no intervening operations on the file take place, then the next
invocation of the lastModified() method will return the (possibly truncated) time
argument that was passed to this method.
Parameters:
time - The new last-modified time, measured in milliseconds since the epoch (00:00:00 GMT,
January 1, 1970)
Returns:
true if and only if the operation succeeded; false otherwise
Throws:
IllegalArgumentException - If the argument is negative
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method denies write access to the named file
JAVA PROGRAMMING
NASC –CS&IT
setReadOnly
public boolean setReadOnly()
Marks the file or directory named by this abstract pathname so that only read operations are
allowed. After invoking this method the file or directory is guaranteed not to change until it is
either deleted or marked to allow write access. Whether or not a read-only file or directory may
be deleted depends upon the underlying system.
Returns:
true if and only if the operation succeeded; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method denies write access to the named file
listRoots
public static File[] listRoots()
List the available filesystem roots.
A particular Java platform may support zero or more hierarchically-organized file
systems. Each file system has a root directory from which all other files in that file
system can be reached. Windows platforms, for example, have a root directory for each
active drive; UNIX platforms have a single root directory, namely "/". The set of
available filesystem roots is affected by various system-level operations such the
insertion or ejection of removable media and the disconnecting or unmounting of
physical or virtual disk drives.
This method returns an array of File objects that denote the root directories of the
available filesystem roots. It is guaranteed that the canonical pathname of any file
physically present on the local machine will begin with one of the roots returned by this
method.
The canonical pathname of a file that resides on some other machine and is accessed via a
remote-filesystem protocol such as SMB or NFS may or may not begin with one of the
roots returned by this method. If the pathname of a remote file is syntactically
indistinguishable from the pathname of a local file then it will begin with one of the roots
returned by this method. Thus, for example, File objects denoting the root directories of
the mapped network drives of a Windows platform will be returned by this method, while
File objects containing UNC pathnames will not be returned by this method.
Unlike most methods in this class, this method does not throw security exceptions. If a
security manager exists and its SecurityManager.checkRead(java.lang.String)
JAVA PROGRAMMING
NASC –CS&IT
method denies read access to a particular root directory, then that directory will not
appear in the result.
Returns:
An array of File objects denoting the available filesystem roots, or null if the set of roots could not
be determined. The array will be empty if there are no filesystem roots.
createTempFile
public static File createTempFile(String prefix,
String suffix,
File directory)
throws IOException
Creates a new empty file in the specified directory, using the given prefix and suffix
strings to generate its name. If this method returns successfully then it is guaranteed that:
1. The file denoted by the returned abstract pathname did not exist before this method was
invoked, and
2. Neither this method nor any of its variants will return the same abstract pathname again
in the current invocation of the virtual machine.
This method provides only part of a temporary-file facility. To arrange for a file created by this
method to be deleted automatically, use the deleteOnExit() method.
The prefix argument must be at least three characters long. It is recommended that the
prefix be a short, meaningful string such as "hjb" or "mail". The suffix argument may
be null, in which case the suffix ".tmp" will be used.
To create the new file, the prefix and the suffix may first be adjusted to fit the limitations
of the underlying platform. If the prefix is too long then it will be truncated, but its first
three characters will always be preserved. If the suffix is too long then it too will be
truncated, but if it begins with a period character ('.') then the period and the first three
characters following it will always be preserved. Once these adjustments have been made
the name of the new file will be generated by concatenating the prefix, five or more
internally-generated characters, and the suffix.
If the directory argument is null then the system-dependent default temporary-file
directory will be used. The default temporary-file directory is specified by the system
property java.io.tmpdir. On UNIX systems the default value of this property is
typically "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically
"c:\\temp". A different value may be given to this system property when the Java
JAVA PROGRAMMING
NASC –CS&IT
virtual machine is invoked, but programmatic changes to this property are not guaranteed
to have any effect upon the the temporary directory used by this method.
Parameters:
prefix - The prefix string to be used in generating the file's name; must be at least three characters
long
suffix - The suffix string to be used in generating the file's name; may be null, in which case the
suffix ".tmp" will be used
directory - The directory in which the file is to be created, or null if the default temporary-file
directory is to be used
Returns:
An abstract pathname denoting a newly-created empty file
Throws:
IllegalArgumentException - If the prefix argument contains fewer than three characters
IOException - If a file could not be created
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method does not allow a file to be created
createTempFile
public static File createTempFile(String prefix,
String suffix)
throws IOException
Creates an empty file in the default temporary-file directory, using the given prefix and suffix to
generate its name. Invoking this method is equivalent to invoking
createTempFile(prefix, suffix, null).
Parameters:
prefix - The prefix string to be used in generating the file's name; must be at least three characters
long
suffix - The suffix string to be used in generating the file's name; may be null, in which case the
suffix ".tmp" will be used
Returns:
JAVA PROGRAMMING
NASC –CS&IT
An abstract pathname denoting a newly-created empty file
Throws:
IllegalArgumentException - If the prefix argument contains fewer than three characters
IOException - If a file could not be created
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String)
method does not allow a file to be created
compareTo
public int compareTo(File pathname)
Compares two abstract pathnames lexicographically. The ordering defined by this method
depends upon the underlying system. On UNIX systems, alphabetic case is significant in
comparing pathnames; on Microsoft Windows systems it is not.
Parameters:
pathname - The abstract pathname to be compared to this abstract pathname
Returns:
Zero if the argument is equal to this abstract pathname, a value less than zero if this abstract
pathname is lexicographically less than the argument, or a value greater than zero if this abstract
pathname is lexicographically greater than the argument
compareTo
public int compareTo(Object o)
Compares this abstract pathname to another object. If the other object is an abstract pathname,
then this function behaves like compareTo(File). Otherwise, it throws a ClassCastException, since
abstract pathnames can only be compared to abstract pathnames.
Specified by:
compareTo in interface Comparable
Parameters:
o - The Object to be compared to this abstract pathname
Returns:
JAVA PROGRAMMING
NASC –CS&IT
If the argument is an abstract pathname, returns zero if the argument is equal to this abstract
pathname, a value less than zero if this abstract pathname is lexicographically less than the
argument, or a value greater than zero if this abstract pathname is lexicographically greater than
the argument
Throws:
ClassCastException - if the argument is not an abstract pathname
See Also:
Comparable
equals
public boolean equals(Object obj)
Tests this abstract pathname for equality with the given object. Returns true if and only if the
argument is not null and is an abstract pathname that denotes the same file or directory as this
abstract pathname. Whether or not two abstract pathnames are equal depends upon the underlying
system. On UNIX systems, alphabetic case is significant in comparing pathnames; on Microsoft
Windows systems it is not.
Overrides:
equals in class Object
Parameters:
obj - The object to be compared with this abstract pathname
Returns:
true if and only if the objects are the same; false otherwise
See Also:
Object.hashCode(), Hashtable
hashCode
public int hashCode()
Computes a hash code for this abstract pathname. Because equality of abstract pathnames is
inherently system-dependent, so is the computation of their hash codes. On UNIX systems, the
hash code of an abstract pathname is equal to the exclusive or of its pathname string and the
decimal value 1234321. On Microsoft Windows systems, the hash code is equal to the exclusive
or of its pathname string, convered to lower case, and the decimal value 1234321.
Overrides:
JAVA PROGRAMMING
NASC –CS&IT
hashCode in class Object
Returns:
A hash code for this abstract pathname
See Also:
Object.equals(java.lang.Object), Hashtable
toString
public String toString()
Returns the pathname string of this abstract pathname. This is just the string returned by the
getPath() method.
Overrides:
toString in class Object
Returns:
The string form of this abstract pathname
JAVA.IO CLASS OVERVIEW
Introduction
This section introduces the basic organization of the java.io classes, consisting of:
* Input and output streams
* Readers and writers
* Data and object I/O streams
Input stream classes
In the InputStream class, bytes can be read from three different sources:
* An array of bytes
JAVA PROGRAMMING
NASC –CS&IT
* A file
* A pipe
Sources, such as ByteArrayInputStream and FilterInputStream, subclass the
InputStream class. The subclasses under InflatorInputStream and
FilterInputStream are listed in the figure below.
InputStream methods
Various methods are included in the InputStream class.
* abstract int read() reads a single byte, an array, or a subarray of bytes. It returns
the bytes read, the number of bytes read, or -1 if end-of-file has been reached.
* read(), which takes the byte array, reads an array or a subarray of bytes and returns a
-1 if the end-of-file has been reached.
* skip(), which takes long, skips a specified number of bytes of input and returns the
number of bytes actually skipped.
* available() returns the number of bytes that can be read without blocking. Both the
input and output can block threads until the byte is read or written.
JAVA PROGRAMMING
NASC –CS&IT
* close() closes the input stream to free up system resources.
InputStream marking
Some, but not all, InputStreams support marking. Marking allows you to go back to a
marked place in the stream like a bookmark for future reference. Remember, not all
InputStreams support marking. To test if the stream supports the mark() and reset()
methods, use the boolean markSupported() method.
The mark() method, which takes an integer read_limit, marks the current position in
the input stream so that reset() can return to that position as long as no more than the
specified number of bytes have been read between the mark() and reset().
OutputStream classes
Bytes can be written to three different types of sinks:
* An array of bytes
* A file
* A pipe
The following figure shows OutputStream classes.
Let's
JAVA PROGRAMMING
NASC –CS&IT
Let's look at some examples of OutputStream classes. Before sending an OutputStream
to its ultimate destination, you can filter it. For example, the BufferedOutputStream is a
subclass of the FilterOutputStream that stores values to be written in a buffer and writes
them out only when the buffer fills up.
CheckedOutputStream and DigestOutputStream are part of the
FilterOutputStream class. They calculate checksums or message digests on the output.
DeflatorOutputStream writes to an OutputStream and creates a zip file. This class
does compression on the fly.
The PrintStream class is also a subclass of FilterOutputStream, which implements a
number of methods for displaying textual representation of Java primitive types. For
example:
* println(long)
* println(int)
println(float)
* println(char)
JAVA PROGRAMMING
NASC –CS&IT
DataOutputStream implements the DataOutput interface. DataOutput defines the
methods required for streams that can write Java primitive data types in a
machine-independent binary format.
OutputStream methods
The OutputStream class provides several methods:
* The abstract void write() method takes an integer byte and writes a single byte.
* The void write() method takes a byte array and writes an array or subarray of
bytes.
* The void flush() method forces any buffered output to be written.
* The void close() method closes the stream and frees up system resources.
It is important to close your output files because sometimes the buffers do not get completely
flushed and, as a consequence, are not complete.
DataInput and DataOutput
The DataInput and DataOutput classes define the methods required for streams that can
read Java primitive data types in a machine-independent binary format. They are
implemented by RandomAccessFile.
The ObjectInput interface extends the DataInput interface and adds methods for
deserializing objects and reading bytes and arrays of bytes. You can learn more about
serialization in Object serialization on page 46.
The ObjectOutputStream class creates a stream of objects that can be deserialized by
the ObjectInputStream class.
The ObjectOutput interface extends the DataOutput interface and adds methods for
serializing objects and writing bytes and arrays of bytes.
ObjectOutputStream is used to serialize objects, arrays, and other values to a stream.
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
JAVA PROGRAMMING
NASC –CS&IT
What are Readers?
Readers are character-based input streams that read Unicode characters.
* read() reads a single character and returns a character read as an integer in the range from to 65535 or a
-1 if the end of thestream is reached.
* abstract read() reads characters into a portion of an array (starting at offset up to length number of
characters) and returns the number of characters read or -1 if the end of
the stream is reached.
int read()
read (char[] buffer,
int offset, int length
Character input streams
Let's take a look at the different character input streams in the java.io package.
* Strings
* Character arrays
* Pipes
InputStreamReader is a character input stream that uses a byte input stream as its data
source and converts it into Unicode characters.
LineNumberReader, a subclass of BufferedReader, is a character input stream that
keeps track of the number of lines of text that have been read from it.
PushbackReader, a subclass of FilterReader, is a character input stream that uses
another input stream as its input source and adds the ability to push characters back onto the
stream.
What are Writers?
Writers are character-based output streams that write character bytes and turn Unicode into bytes.
The base class includes these methods:
JAVA PROGRAMMING
NASC –CS&IT
* The void write() method, which takes acharacter and writes single character in 16 low-order bits
* The abstract void write() method,which takes a character array and writes a portion of an array of
characters
void write(int character)
void write(char[] buffer,
int offset, int length)
Character output streams
Let's take a look at the different character output streams in the java.io package. There
are several branches of this inheritance tree you can explore. Like Readers, any of the
branches are available. Sinks for Writer output can be:
* Strings
* CharArray
* Pipes
OutputStreamWriter uses a byte output stream as the destination for its data.
BufferedWriter applies buffering to a character output stream, thus improving output efficiency by
combining many small write requests into a single large request.
FilterWriter is an abstract class that acts as a superclass for character output streams.
The streams filter the data written to them before writing it to some other character output stream.
PrintWriter is a character output stream that implements print() and println() methods that output textual
representations of primitive values and objects.
Presented by developerWorks, your source for great tutorials ibm.com/developerWorks
The File Class
Files and directories are accessed and manipulated via the java.io.File class. The File class does not
actually provide for input and output to files. It simply provides an identifier of files and directories.
Always remember that just because a File object is created, it does not mean there actually exists on the
disk a file with the identifier held by that File object.
JAVA PROGRAMMING
NASC –CS&IT
The File class includes several overloaded constructors. For example, the following instance of File refers
to a file named myfile.txt in the current directory of the program that the JVM is running:
File file = new File ("myfile.txt");
Again, the file myfile.txt may or may not exist in the file system. An attempt to use File object that refers
to a file that does not exist will cause a FileNotFoundException to be thrown.
The File instance can also created with a filename that includes path:
File fileA = new File("/tmp/filea.txt");
Another overloaded constructor allows separate specification of the path and the file name:
File fileA = new File("/tmp", "filea.txt");
Directories can also be specified:
File direc = new File("/tmp");
There are a number of useful methods in File, e.g.:
Boolean exist();
- does the file exist
Boolean canWrite();
- can the file be written to
Boolean canRead();
- can the file be read
Boolean isFile();
- does it represent a file
Boolean isDirectory(); - or a directory
There are also methods to get the file name and path components, to make a directory, to get a listing of
the files in a directory, etc.
String getName () - get the name of the file (no path included)
String getPath () - get the abstract file path
String getCanonicalPath () - get the name of the file with path
String getAbsolutePath () - get the absolute file path
Note that path names use different separator characters on different hosts. Windows uses "\", Unix"/",
Macintosh ":". The static variables:
File.separator - string with file separator
JAVA PROGRAMMING
NASC –CS&IT
File.separatorChar - char with file separator
File.pathSeparator - string with path separator
File.pathSeparatorChar - char with path separator
can be used to insure that your programs are platform independent. For example, this snippet shows how
to build a platform independent path:
String dirName = "dataDir";
String filename = "data.dat";
File filData = new File(dirName + File.separator + filename);
Other talents of the File class include the method
boolean mkdir ()
This method will create a directory with the abstract path name represented by the File object if that File
object represents a directory. The method returns true if the directory creation succeeds and false if not. A
situation in which the directory cannot be created is, for example, when the File object refers to an actual
file that already exists in the file system.
CLASS I/O EXCEPTION
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
Direct Known Subclasses:
ChangedCharSetException, CharacterCodingException, CharConversionException,
ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException,
FilerException, HttpRetryException, IIOException, InterruptedIOException,
InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException,
MalformedURLException, ObjectStreamException, ProtocolException, RemoteException,
SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException,
UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException,
UTFDataFormatException, ZipException
--------------------------------------------------------------------------------
JAVA PROGRAMMING
NASC –CS&IT
public class IOExceptionextends ExceptionSignals that an I/O exception of some sort has occurred. This
class is the general class of exceptions produced by failed or interrupted I/O operations.
Constructor
IOException()
Constructs an IOException with null as its error detail message.
IOException(String message)
Constructs an IOException with the specified detail message.
IOException(String message, Throwable cause)
Constructs an IOException with the specified detail message and cause.
IOException(Throwable cause)
Constructs an IOException with the specified cause and a detail message of (cause==null ? null :
cause.toString()) (which typically contains the class and detail message of cause).
Method Summary
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause,
printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Constructor Detail
IOException
public IOException()Constructs an IOException with null as its error detail message.
-------------------------------------------------------------------------------IOException
public IOException(String message)Constructs an IOException with the specified detail message.
Parameters:
message - The detail message (which is saved for later retrieval by the Throwable.getMessage() method)
JAVA PROGRAMMING
NASC –CS&IT
-------------------------------------------------------------------------------IOException
public IOException(String message,
Throwable cause)Constructs an IOException with the specified detail message and cause.
Note that the detail message associated with cause is not automatically incorporated into this exception's
detail message.
Parameters:
message - The detail message (which is saved for later retrieval by the Throwable.getMessage() method)
cause - The cause (which is saved for later retrieval by the Throwable.getCause() method). (A null value
is permitted, and indicates that the cause is nonexistent or unknown.)
-------------------------------------------------------------------------------IOException
public IOException(Throwable cause)Constructs an IOException with the specified cause and a detail
message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message
of cause). This constructor is useful for IO exceptions that are little more than wrappers for other
throwables.
Parameters:
cause - The cause (which is saved for later retrieval by the Throwable.getCause() method). (A null value
is permitted, and indicates that the cause is nonexistent or unknown.)
Reading, Writing, and Creating Files
This page discusses the details of reading, writing, creating, and opening files. Three of the methods used
to create a new file enable you to specify an optional set of initial attributes for the file. For example, on a
file system that supports the POSIX set of standards (such as UNIX), you can specify a file owner, group
owner, or file permissions at the time the file is created. Before reading this page, first familiarize yourself
with file attributes in Managing Metadata.
JAVA PROGRAMMING
NASC –CS&IT
File I/O
The java.nio.file package supports stream I/O by using regular input stream and output stream API for
reading and writing. This package is fully interoperable with the java.io package. The following sections
cover this form of I/O:
Reading a File by Using Stream I/O
Creating and Writing a File by using Stream I/O
The java.nio.file package also supports channel I/O, which moves data in buffers, bypassing some of the
layers that can bottleneck stream I/O. The channel I/O methods are covered in Reading and Writing Files
by Using Channel I/O.
The other topic covered in this page is Creating Files.
Creating Files
You can create an empty file with an initial set of attributes by using the createFile(FileAttribute<?>)
method. For example, if, at the time of creation, you want a file to have particular set of file permissions,
use the createFile method to do so. If you do not specify any attributes, the file is created with default
attributes. If the file already exists, createFile throws an exception.
In a single atomic operation, the createFile method checks for the existence of the file and creates that file
with the specified attributes, which makes the process more secure against malicious code.
The following code snippet creates a file with default attributes:
Path file = ...;
try {
JAVA PROGRAMMING
NASC –CS&IT
file.createFile(); //Create the empty file with default permissions, etc.
} catch (FileAlreadyExists x) {
System.err.format("file named %s already exists%n", file);
} catch (IOException x) {
//Some other sort of failure, such as permissions.
System.err.format("createFile error: %s%n", x);
}
POSIX File Permissions has an example that uses createFile(FileAttribute<?>) to create a file with pre-set
permissions.
You can also create a new file by using the newOutputStream methods, as described in Creating and
Writing a File using Stream I/O. If you open a new output stream and close it immediately, an empty file
is created.
Reading a File by Using Stream I/O
To open a file for reading, you can use the newInputStream(OpenOption...) method. This method returns
an unbuffered input stream for reading bytes from the file.
Path file = ...;
InputStream in = null;
try {
in = file.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
JAVA PROGRAMMING
NASC –CS&IT
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.println(x);
} finally {
if (in != null) in.close();
}
Creating and Writing a File by Using Stream I/O
You can create a file, append to a file, or write to a file by using one of the newOutputStream methods:
newOutputStream(OpenOption...)
newOutputStream(Set<? extends OpenOption>, FileAttribute<?>...)
These methods open or create a file for writing bytes and return an unbuffered output stream. Both
methods take a list of OpenOption options. The second method enables you to specify initial file
attributes, similar to the createFile(FileAttribute<?>) method. The first method takes the options as a
varargs argument, and the second method takes the options as a Set. This difference might seem
confusing, but a method can only accept a single varargs argument.
The following StandardOpenOptions enums are supported:
WRITE – Opens the file for write access.
APPEND – Appends the new data to the end of the file. This option is used with the WRITE or CREATE
options.
TRUNCATE_EXISTING – Truncates the file to zero bytes. This option is used with the WRITE option.
JAVA PROGRAMMING
NASC –CS&IT
CREATE_NEW – Creates a new file and throws an exception if the file already exists.
CREATE – Opens the file if it exists or creates a new file if it does not.
DELETE_ON_CLOSE – Deletes the file when the stream is closed. This option is very useful for
temporary files.
SPARSE – Hints that a newly created file will be sparse. This advanced option is honored on some file
systems, such as NTFS, where large files with data "gaps" can be stored in a more efficient manner where
those empty gaps do not consume disk space.
SYNC – Keeps the file (both content and metadata) synchronized with the underlying storage device.
DSYNC – Keeps the file content synchronized with the underlying storage device.
If no open options are specified, and the file does not exist, a new file is created. If the file exists, it is
truncated. This optoin is equivalent to invoking the method with the CREATE and
TRUNCATE_EXISTING options.
The following code snippet opens a log file. If the file does not exist, it is created. If the file exists, it is
opened for appending.
import static java.nio.file.StandardOpenOption.*;
Path logfile = ...;
//Convert the string to a byte array.
String s = ...;
byte data[] = s.getBytes();
OutputStream out = null;
try {
out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND));
...
JAVA PROGRAMMING
NASC –CS&IT
out.write(data, 0, data.length);
} catch (IOException x) {
System.err.println(x);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
Reading and Writing Files by Using Channel I/O
While stream I/O reads a character at a time, channel I/O reads a buffer at a time. The ByteChannel
interface provides basic read and write functionality. A SeekableByteChannel is a ByteChannel that has
the capability to maintain a position in the channel and to change that position. A SeekableByteChannel
also supports truncating the file associated with the channel and querying the file for its size.
The capability to move to different points in the file and then read from or write to that location makes
random access of a file possible. See Random Access Files for more information.
There are two methods for reading and writing channel I/O. The method signatures for the
newByteChannel methods are almost identical to the newOutputStream methods, and they are invoked
similarly.
newByteChannel(OpenOption...)
newByteChannel(Set<? extends OpenOption>, FileAttribute<?>...)
JAVA PROGRAMMING
NASC –CS&IT
-------------------------------------------------------------------------------Note: The newByteChannel methods return an instance of a SeekableByteChannel. With a default file
system, you can cast this seekable byte channel to a FileChannel providing access to more advanced
features such mapping a region of the file directly into memory for faster access, locking a region of the
file so other processes cannot access it, or reading and writing bytes from an absolute position without
affecting the channel's current position.
--------------------------------------------------------------------------------
Both newByteChannel methods enable you to specify a list of OpenOption options. The same open
options used by the newOutputStream methods are supported, in addition to one more option: READ is
required because the SeekableByteChannel supports both reading and writing.
Specifying READ opens the channel for reading. Specifying WRITE or APPEND opens the channel for
writing. If none of these options is specified, the channel is opened for reading.
The following code snippet reads a file and prints it to standard output:
SeekableByteChannel sbc = null;
try {
sbc = file.newByteChannel(); //Defaults to READ
ByteBuffer buf = ByteBuffer.allocate(10);
//Read the bytes with the proper encoding for this platform.
//If you skip this step, you might see something that looks like Chinese
//characters when you expect Latin-style characters.
String encoding = System.getProperty("file.encoding");
while (sbc.read(buf) > 0) {
buf.rewind();
JAVA PROGRAMMING
NASC –CS&IT
System.out.print(Charset.forName(encoding).decode(buf));
buf.flip();
}
} catch (IOException x) {
System.out.println("caught exception: " + x);
} finally {
if (sbc != null) sbc.close();
}
The following code snippet, written for UNIX and other POSIX file systems, creates a log file with a
specific set of file permissions. This code creates a log file or appends to the log file if it already exists.
The log file is created with read/write permissions for owner and read only permissions for group.
import static java.nio.file.StandardCopyOption.*;
//Create the set of options for appending to the file.
Set<OpenOptions> options = new HashSet<OpenOption>();
options.add(APPEND);
options.add(CREATE);
//Create the custom permissions attribute.
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-r------");
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
//Convert the string to a ByetBuffer.
String s = ...;
JAVA PROGRAMMING
NASC –CS&IT
byte data[] = s.getBytes();
ByteBuffer bb = ByteBuffer.wrap(data);
SeekableByteChannel sbc = null;
try {
sbc = file.newByteChannel(options, attr);
sbc.write(bb);
} catch (IOException x) {
System.out.println("exception thrown: " + x);
} finally {
if (sbc != null) sbc.close();
}
Random Access Files
Random access files permit nonsequential, or random, access to a file's contents. To access a file
randomly, you open the file, seek a particular location, and read from or write to that file.
This functionality is possible with the SeekableByteChannel interface. The SeekableByteChannel
interface extends channel I/O with the notion of a current position. Methods enable you to set or query the
position, and you can then read the data from, or write the data to, that location. The API consists of a
few, easy to use, methods:
position – Returns the channel's current position
position(long) – Sets the channel's position
read(ByteBuffer) – Reads bytes into the buffer from the channel
write(ByteBffer) – Writes bytes from the buffer to the channel
JAVA PROGRAMMING
NASC –CS&IT
truncate(long) – Truncates the file (or other entity) connected to the channel
Reading and Writing Files With Channel I/O shows that the Path.newByteChannel methods return an
instance of a SeekableByteChannel. On the default file system, you can use that channel as is, or you can
cast it to a FileChannel giving you access to more advanced features, such as mapping a region of the file
directly into memory for faster access, locking a region of the file, or reading and writing bytes from an
absolute location without affecting the channel's current position.
The following code snippet opens a file for both reading and writing by using one of the newByteChannel
methods. The SeekableByteChannel that is returned is cast to a FileChannel. Then, 12 bytes are read from
the beginning of the file, and the string "I was here!" is written at that location. The current position in the
file is moved to the end, and the 12 bytes from the beginning are appended. Finally, the string, "I was
here!" is appended, and the channel on the file is closed.
String s = "I was here!\n";
byte data[] = s.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);
ByteBuffer copy = ByteBuffer.allocate(12);
FileChannel fc = null;
try {
fc = (FileChannel)file.newByteChannel(READ, WRITE);
//Read the first 12 bytes of the file.
int nread;
do {
nread = fc.read(copy);
} while (nread != -1 && copy.hasRemaining());
//Write "I was here!" at the beginning of the file.
JAVA PROGRAMMING
fc.position(0);
while (out.hasRemaining())
fc.write(out);
out.rewind();
//Move to the end of the file. Copy the first 12 bytes to
//the end of the file. Then write "I was here!" again.
long length = fc.size();
fc.position(length-1);
copy.flip();
while (copy.hasRemaining())
fc.write(copy);
while (out.hasRemaining())
fc.write(out);
} catch (IOException x) {
System.out.println("I/O Exception: " + x);
} finally {
//Close the file.
if (fc != null) fc.close();
System.out.println(file + " has been modified!");
}
Java - Streams, Files and I/O
--------------------------------------------------------------------------------
NASC –CS&IT
JAVA PROGRAMMING
NASC –CS&IT
--------------------------------------------------------------------------------
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in
Java. All these streams represent an input source and an output destination. The stream in the java.io
package supports many data such as primitives, Object, localized characters etc.
A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the
OutputStream is used for writing data to a destination.
Java does provide strong, flexible support for I/O as it relates to files and networks but this tutorial covers
very basic functionlity related to streams and I/O. We would see most commonly used example one by
one:
Reading Console Input:
Java input console is accomplished by reading from System.in. To obtain a character-based stream that is
attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. Here
is most common syntax to obtain BufferedReader:
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Once BufferedReader is obtained, we can use read( ) method to reach a character or readLine( ) method to
read a string from the console.
Reading Characters from Console:
To read a character from a BufferedReader, we would read( ) method whose sytax is as follows:
JAVA PROGRAMMING
NASC –CS&IT
int read( ) throws IOException
Each time that read( ) is called, it reads a character from the input stream and returns it as an integer
value. It returns .1 when the end of the stream is encountered. As you can see, it can throw an
IOException.
The following program demonstrates read( ) by reading characters from the console until the user types a
"q":
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
JAVA PROGRAMMING
NASC –CS&IT
} while(c != 'q');
}
}
Here is a sample run:
Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q
Reading Strings from Console:
To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader
class. Its general form is shown here:
String readLine( ) throws IOException
The following program demonstrates BufferedReader and the readLine( ) method. The program reads and
displays lines of text until you enter the word "end":
JAVA PROGRAMMING
// Read a string from console using a BufferedReader.
import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException
{
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'end' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("end"));
}
}
Here is a sample run:
Enter lines of text.
Enter 'end' to quit.
This is line one
This is line one
NASC –CS&IT
JAVA PROGRAMMING
NASC –CS&IT
This is line two
This is line two
end
end
Writing Console Output:
Console output is most easily accomplished with print( ) and println( ), described earlier. These methods
are defined by the class PrintStream which is the type of the object referenced by System.out. Even
though System.out is a byte stream, using it for simple program output is still acceptable.
Because PrintStream is an output stream derived from OutputStream, it also implements the low-level
method write( ). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined
by PrintStream is shown here:
void write(int byteval)
This method writes to the stream the byte specified by byteval. Although byteval is declared as an integer,
only the low-order eight bits are written.
Example:
Here is a short example that uses write( ) to output the character "A" followed by a newline to the screen:
import java.io.*;
// Demonstrate System.out.write().
class WriteDemo {
JAVA PROGRAMMING
NASC –CS&IT
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
This would produce simply 'A' character on the output screen.
READING AND WRITING FILES:
As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read data
from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.
The two important streams are FileInputStream and FileOutputStream which would be discussed in this
tutorial:
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new and
there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file.:
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we create a
file object using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
JAVA PROGRAMMING
NASC –CS&IT
Once you have InputStream object in hand then there is a list of helper methods which can be used to
read to stream or to do other operations on the stream.
SN Methods with Description
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file. Throws
an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream
is called when there are no more references to this stream. Throws an IOException.
3 public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte
of data and -1 will be returned if it's end of file.
4 public int read(byte[] r) throws IOException{}
This method reads r.length bytes from the input stream into an array. Returns the total number of bytes
read. If end of file -1 will be returned.
5 public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream. Returns an int.
There are other important input streams available, for more detail you can refer to the following links:
FileOutputStream:
FileOutputStream is used to create a file and write data into it.The stream would create a file, if it doesn't
already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the file.:
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First we create
a file object using File() method as follows:
File f = new File("C:/java/hello");
JAVA PROGRAMMING
NASC –CS&IT
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand then there is a list of helper methods which can be used to
write to stream or to do other operations on the stream.
SN Methods with Description
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file. Throws
an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream
is called when there are no more references to this stream. Throws an IOException.
3 public void write(int w)throws IOException{}
This methods writes the specified byte to the output stream.
4 public void write(byte[] w)
Writes w.length bytes from the mentioned byte array to the OutputStream.
There are other important output streams available, for more detail you can refer to the following links:
ByteArrayOutputStream
DataOutputStream
Example:
Following is the example to demonstrate InputStream and OutputStream:
import java.io.*;
public class fileStreamTest{
public static void main(String args[]){
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("C:/test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
JAVA PROGRAMMING
NASC –CS&IT
}
os.close();
InputStream is = new FileInputStream("C:/test.txt");
int size = is.available();
for(int i=0; i< size; i++){
System.out.print((char)is.read() + " ");
}
is.close();
}catch(IOException e){
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given numbers in binary format. Same would
be output on the stdout screen.
File Navigation and I/O:
There are several other classes that we would be going through to get to know the basics of File
Navigation and I/O.
Creating Directories:
There are two useful File utility methods which can be used to create directories:
The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates
that the path specified in the File object already exists, or that the directory cannot be created because the
entire path does not exist yet.
The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory:
import java.io.File;
JAVA PROGRAMMING
NASC –CS&IT
class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}
Compile and execute above code to create "/tmp/user/java/bin".
Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you
use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.
Reading Directories:
A directory is a File that contains a list of other files and directories. When you create a File object and it
is a directory, the isDirectory( ) method will return true.
You can call list( ) on that object to extract the list of other files and directories inside. The program
shown here illustrates how to use list( ) to examine the contents of a directory:
import java.io.File;
class DirList {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println( "Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
JAVA PROGRAMMING
NASC –CS&IT
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}
HANDLING PRIMITIVE DATA TYPES
The basic input and output streams provide read/write methods that can be used for
reading/writing bytes or characters.
To read/write the primitive data types such as integers and doubles, we can use filter classes as
wrappers on the existing I /O streams to lter data to the original stream.
JAVA PROGRAMMING
NASC –CS&IT
The two filter classes supported for creating “data streams” for primitive data types are:
DataInputStream
DataOutputStream
Data Input Stream Creation
� Create Input File Stream:
_ FileInputStream fis = new FileInputStream(“InFile”);
� Create Input Data Stream:
_ DataInputStream dis = new DataInputStream( fis );
_ The above statements wrap data input stream (dis) on file input stream (fis) and use it as a
filter”.
_ Methods Supported:
_ readBoolean(), readByte(), readChar(), readShort(), readInt(),
readLong(), readFloat(), readDouble()
_ They read data stored in file in binary format.
Data Output Stream Creation
� Create Output File Stream:
FileOutputStream fos = new FileOutputStream(“OutFile”);
� Create Output Data Stream:
DataOutputStream dos = new DataOutputStream( fos );
The above statements wrap data output stream (dos) on file output stream (fos) and use it as a
“filter”.
Methods Supported:
writeBoolean(), writeByte(), writeChar(), writeShort(),writeInt(), writeLong(), writeFloat(),
writeDouble()
They write data to file in binary format.
How many bytes are written to file when for statements:
JAVA PROGRAMMING
writeInt(120), writeInt(10120)
Writing and Reading Primitive Data
import java.io.* ;
public class ReadWriteFilter {
public static void main(String args[ ] ) throws I OException {
/ / write primitive data in binary format to the "mydata" file
FileOutputStream fos = new FileOutputStream( "mydata") ;
DataOutputStream dos = new DataOutputStream( fos) ;
dos.writeI nt(120) ;
dos.writeDouble(375.50) ;
dos.writeI nt( ’A’+ 1) ;
dos.writeBoolean( true) ;
dos.writeChar( ’X’) ;
dos.close( ) ;
fos.close( ) ;
/ / read primitive data in binary format from the "mydata" file
FileI nputStream fis = new FileI nputStream( "mydata") ;
DataI nputStream dis = new DataI nputStream( fis) ;
System.out.println(dis.readI nt( ) ) ;
System.out.println(dis.readDouble( ) ) ;
System.out.println(dis.readI nt( ) ) ;
System.out.println(dis.readBoolean( ) ) ;
System.out.println(dis.readChar( ) ) ;
dis.close( ) ;
NASC –CS&IT
JAVA PROGRAMMING
NASC –CS&IT
fis.close( ) ;
}
}
Program Run and Output
C:\254\examples>java ReadWriteFilter
120
375.5
66
true
X
� Display content of “mydata” file (in binary format):
C:\254\examples>type mydata
x@wx B X
� What is the size of “mydata” file (in bytes) ?
Size of int+double+int+boolean+char
Concatenating and Buffering Streams
� Two or more input streams can be combined into a single input stream. This process is known
as logical concatenation of streams and is achieved using the SequenceInputStream class.
� A SequenceInputStream starts out with an ordered collection of input streams and reads
from the first one until end of file is reached, whereupon it reads from the second one, and
so on, until end of file is reached on the last of the contained input streams.
Sequencing and Buffering of Streams
� Buffered streams sit between the program and data source/destination and functions like a
JAVA PROGRAMMING
NASC –CS&IT
filter or support efficient I /O. Buffered can be created using BufferedInputStream and
BufferedOutputStream classes.
Example Program
import java.io.* ;
public class CombineStreams {
public static void main(String args[ ] ) throws I OException {
/ / declare file streams
FileI nputStream file1 = new FileI nputStream( "file1.dat") ;
FileI nputStream file2 = new FileI nputStream( "file2.dat") ;
/ / declare file3 to store combined streams
SequenceI nputStream file3 = null;
/ / concatenate file1 and file2 streams into file3
file3 = new SequenceI nputStream( file1, file2) ;
BufferedI nputStream inBuffer = new BufferedI nputStream( file3) ;
BufferedOutputStream outBuffer = new BufferedOutputStream(System.out) ;
/ / read and write combined streams until the end of buffers
int ch;
while( (ch = inBuffer.read( ) ) != -1 )
outBuffer.write(ch) ;
outBuffer.flush( ) ; / / check out the output by removing this line
System.out.println( "\ nHello, This output is generated by CombineFiles.java program") ;
inBuffer.close( ) ;
outBuffer.close( ) ;
JAVA PROGRAMMING
NASC –CS&IT
file1.close( ) ;
file2.close( ) ;
file3.close( ) ;
}
}
Random Access Files
So for we have discussed sequential files that are either used for storing data and accessed
(read/write) them in sequence.
In most real world applications, it is necessary to access data in non-sequential order (e.g,
banking system) and append new data or update existing data.
Java IO package supports RandomAccessFile class that allow us to create files that can be
used for reading and/or writing with random access.
The file can be open either in read mode (“r”) or readwrite mode (“rw”) as follows:
� myFileHandleName = new RandomAccessFile (“filename ”, “mode”);
The file pointer can be set to any to any location (measured in bytes) using seek() method
prior to reading or writing.
Random Access Example
import java.io.* ;
public class RandomAccess {
public static void main(String args[ ] ) throws I OException {
/ / write primitive data in binary format to the "mydata" file
RandomAccessFile myfile = new RandomAccessFile( "rand.dat", "rw") ;
myfile.writeI nt(120) ;
myfile.writeDouble(375.50) ;
myfile.writeI nt( ’A’+ 1) ;
JAVA PROGRAMMING
NASC –CS&IT
myfile.writeBoolean( true) ;
myfile.writeChar( ’X’) ;
/ / set pointer to the beginning of file and read next two items
myfile.seek(0) ;
System.out.println(myfile.readI nt( ) ) ;
System.out.println(myfile.readDouble( ) ) ;
/ / set pointer to the 4th item and read it
myfile.seek(16) ;
System.out.println(myfile.readBoolean( ) ) ;
/ / Go to the end and “append” an integer 2003
myfile.seek(myfile.length( ) ) ;
myfile.writeI nt(2003) ;
/ / read 5th and 6th items
myfile.seek(17) ;
System.out.println(myfile.readChar( ) ) ;
System.out.println(myfile.readI nt( ) ) ;
System.out.println( "File length: "+ myfile.length( ) ) ;
myfile.close( ) ;
}
Streams and Interactive I/O
� Real world applications are designed to support interactive and/or batch I /O operations.
� Interactive programs allow users to interact with them during their execution through I /O
devices such as keyboard, mouse, display devices (text/graphical interface), media
JAVA PROGRAMMING
NASC –CS&IT
devices (microphones/speakers), etc.. Java provides rich functionality for developing
interactive programs.
� Batch programs are those that are designed to read input data from files and produce outputs
through files.
Standard I/O
The System class contains three I /O objects (static)
System.in – instance of InputStream
System.out – instance of PrintStream
System.err – instance of PrintStream
To perform keyboard input, we need use functionalities of DataInputStream and
StringTokenizer classes