Io
Io
1
Recall
2
Console IO
5
Example
import java.io.Console;
import java.util.Arrays;
7
Creating a file using File
File(String pathname)
Creates a new File instance (if relative path is given then it converts
it into abstract pathname)
File(String parent, String child)
File(File parent, String child)
Creates a new File instance from a parent pathname and a child
pathname string. If “parent” is null then it behaves like the single-
argument File constructor
boolean createNewFile() throws IOException
creates a new, empty file if a file with the name (as specified in the
constructor) does not exist and returns true; otherwise it returns false.
Note that this method throws IOException if I/O error occurs
So to create a file:
Create instance of File object
Call createNewFile method
8
Other members in File
static final String separator
system-dependent separator character
boolean delete()
Deletes the file or directory. Directory must be empty in order to be
deleted. Returns true if the delete operation is successful.
void deleteOnExit()
Deletes the file or directory when the virtual machine terminates.
Deletion happen only for normal termination of the virtual machine.
Once deletion has been requested, it is not possible to cancel the
request
boolean renameTo(File dest )
Renames the file . This is system dependent so return value should
always be checked to make sure that the rename operation was
successful 9
boolean mkdir()
Creates the directory named by the pathname. Returns true if the
directory was created; false otherwise
boolean mkdirs()
Creates the directory named by this 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.
boolean isDirectory()
Returns true if the File object denotes a directory; false otherwise.
String getName()
Returns the name of the file or directory . just the last name in the
pathname's name sequence
10
String[] list()
Returns list names files and directories in the directory
boolean isFile()
Returns true if the File object denotes a file; false otherwise.
boolean isHidden()
Returns true if the File object is a hidden file; false otherwise.
boolean exists()
Returns true if the file or directory exists; false otherwise
String getAbsolutePath()
Returns the absolute pathname string of this abstract pathname
long lastModified()
Returns the time that the file object was last modified.
long length()
11
Returns the length of the file, unspecified it is a directory.
New methods added in Java 6
boolean canExecute()
boolean canRead()
boolean canWrite()
Returns true if the application can execute/read/write the file
denoted; false otherwise
boolean setXxx(boolean permission)
setXxx(boolean permission, boolean ownerOnly)
Xxx could be Readable, Executable or Writable
Sets the read/execute/write permission if permission is true
ownerOnly is true then the read/execute/write permission applies
only to the owner's execute permission provided underlying file
system can distinguish between owner and others; otherwise, it
applies to everybody. 12
Example: Creating a file
Creates a new file named newFile.txt. If file exists then it deletes the file
and creates a new one
import java.io.*;
class FileOper{
public static void main(String str[]){
try{
File file = new File("newFile.txt");
if(file.exists())
file.delete();
boolean b=file.createNewFile();
System.out.println(b);
}catch(IOException e){ }
}}
13
What are streams
An IO stream is an abstract term for any type of input or output device.
There are 2 types of stream
Input stream to read data from a source. An input stream may be
files, keyboard, console, other programs, a network, or an array!
Output stream to read data into a destination. An output stream may
be disk files, monitor, a network, other programs, or an array
Fundamentally stream may be
Byte stream : data read or written is in the form of byte
or
Character stream: data read or written is in the form of character
Stream is a sequence of data
14
Stream types in Java
Character stream
Character stream writer classes
Character stream reader classes
Byte stream
Byte stream writer classes
Byte stream reader classes
Supports Serialization
15
Character stream
16
Hierarchy of character stream writer
Writer
CharArrayWriter
StringWriter
OutputStreamWriter FileWriter
BufferedWriter
17
Writer
void write(char[] cbuf)
void write(char[] cbuf, int off, int len)
void write(String str)
void write(String str, int off, int len)
void write(int c)
void close()
void flush()
18
CharArrayWriter
CharArrayWriter allows to write data into char array.
Constructors:
CharArrayWriter()
CharArrayWriter(int initialSize)
Methods
char[] toCharArray()
int size()
String toString()
CharArrayWriter append(char c)
void writeTo(Writer out)
20
OutputStreamWriter
An OutputStreamWriter is a used as a bridge from character
streams to byte streams:
Constructor:
OutputStreamWriter(OutputStream out)
OutputStream is a the top-most class in the byte stream (like
Writer is top-most class in the character stream )
Example:
Writer out = new OutputStreamWriter(System.out);
If you remember out is a member of System class which is of type
PrintStream which is subclass of OutputStream.
public void write(int c)
21
Example : OutputStreamWriter
The code extracts part of string and displays on the console.
Note the way we have used finally to close the stream.
CharArrayReader
BufferedReader LineNumberInputStream
FilterReader PushbackReader
InputStreamReader FileReader
29
…
Reader
Reader is an abstract class for reading character streams.
Methods:
void close()
int read()
int read(char[] cbuf, int off, int len)
void mark(int readAheadLimit)
void reset()
Marks the current position in the stream. When reset() is called after
mark() the file pointer is positioned to the marked position.
readAheadLimit is used to specify how many characters can be read
further from the marked position so as to retain the marked position. If
characters read is greater than what is specified in readAheadLimit,
then calling reset does not position the file pointer in the marked position.
30
long skip(long n)
boolean markSupported()
mark() and reset() are optional methods that is not all
implementing class need to provide the implementation for mark()
and reset(). Therefore before they are used we must test if
they are supported by the implementing class using
markSupported()
31
CharArrayReader and StringReader
The data source for this class is a character array. Therefore reading
happens from here.
CharArrayReader(char[] buf)
CharArrayReader(char[] buf, int offset, int length)
This class supports mark() and reset()
The data source for this class is a character array. Therefore reading
happens from here.
StringReader(String s)
36
FileReader
FileReader is subclass of InputStreamWriter
This class is used to read from a text file.
Constructors:
FileReader(File file) throws FileNotFoundException
FileReader(String fileName) throws
FileNotFoundException
Either filename can be specified as a String or File object is passed to the
FileReader constructor.
If the file specified by the name does not exist a
FileNotFoundException is thrown
FileNotFoundException is a subclass of IOException
37
BufferedReader
Reads text from a character-input stream by buffering characters for
the efficient reading of characters, arrays, and lines.
Constructor:
BufferedReader(Reader in)
BufferedReader(Reader in, int sz)
The default buffer size is large enough for most purposes. In cases
where more is required size can be specified.
Methods:
String readLine() throws IOException
This class supports mark() and reset()
38
LineNumberReader
This class is subclass of BufferedReader. So in addition to providing
buffering it is also used to get and set the line number.
Constructor:
LineNumberReader(Reader in)
LineNumberReader(Reader in, int sz)
Methods:
int getLineNumber()
void setLineNumber(int lineNumber)
By default the line number begins from 0.
This class supports mark() and reset()
39
Example: Reading from a CSV file
Code reads from a CSV file and prints on the console
public static void main(String[] as) throws IOException{
LineNumberReader f2=null;
try{
f2= new LineNumberReader(new
FileReader("D:"+File.separator+"a.csv"));
String s=null;
while((s=f2.readLine())!=null){
StringTokenizer st=new StringTokenizer(s,",");
while(st.hasMoreElements()){
System.out.print(f2.getLineNumber());
System.out.print(" Name:" +st.nextElement());
System.out.print("ID:" +st.nextElement());
System.out.println("Degree:" +st.nextElement());
} } }catch(IOException ioe){}
finally{
try{if(f2!=null)f2.close();} 40
catch(IOException e){}} }}
Hierarchy of byte stream
InputStream
ByteArrayInputStream
FilterInputStream BufferedInputStream
LineNumberInputStream
PushbackInputStream
DataInputStream
41
OutputStream
DataOutput interface
ObjectOutputStream
ByteArrayOutputStream
FilterOutputStream
BufferedOutputStream
Writing happens in
the form of byte. ObjectOutputStream
PrintStream
42
Example: using byte stream
Classes which are not in red in the last 2 slides are similar/parallel to
character stream classes . Only difference is in place of char array
we have byte array. So we end with an example for these classes.
Example below copies the content of one file into another file.
import java.io.*;
public class CopyFile {
public static void main(String[] args) throws
IOException {
File file1 = new File("D:"+File.separator+"read.txt");
File file2 = new
File("D:"+File.separator+"write.txt");
FileInputStream fin=null;
FileOutputStream fout=null;
43
try {
fin = new FileInputStream(file1);
fout = new FileOutputStream (file2);
byte fileContent[] = new byte[(int)file1.length()];
fin.read(fileContent);
String strFileContent = new String(fileContent);
fout.write(fileContent);
System.out.println(strFileContent);
}
catch(FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch(IOException ioe) {
System.out.println("Exception while reading the
file " + ioe);
}
finally{
if(fin!=null)fin.close();
if(fout!=null)fout.close();}}}
44
DataInputStream and
DataOutputStream
A data input stream and data output stream lets an application read
and write primitive Java data types from an underlying input stream
and output stream in a machine-independent way.
An application uses a data output stream to write data that can later
be read by a data input stream and vice versa.
45
DataOutputStream methods
Inherited from OutputStream
void write(int b)
void write(byte[] b, int off, int len)
void writeXxx(xxx v)
xxx readXxx()
import java.io.*;
class Test{
public static void main(String[] st) throws Exception{
DataOutputStream out= new DataOutputStream(new
FileOutputStream("a.txt"));
int i=10;
double d= 12.3;
out.writeInt(i);
out.writeDouble(d);
out.close();
DataInputStream in= new DataInputStream(new
FileInputStream("a.txt"));
System.out.println( in.readInt() );
System.out.println( in.readDouble() );
in.close();
} } 47
PrintStream
PrintStream is a class that has functionality like the ability to
print representations of various data values conveniently.
System.out is an instance of PrintStream.
Apart from this, two other functionalities that are provided here are:
A) Unlike other output streams, a PrintStream never throws an
IOException
B)The flush() method can be made to automatically invoked after
println method is invoked or newline („\n‟) is written.
48
PrintStream members
Constructors:
PrintStream(File file) throws FileNotFoundException
PrintStream(OutputStream out,[boolean autoFlush])
PrintStream(String fileName) throws
FileNotFoundException
( The option in square brackets are optional)
void print(xxx b)
void println(xxx b)
where xxx is any primitive type, String or Object.
PrintStream printf(String format, Object... args)
PrintStream format(String format, Object... args)
Both of the above methods have same functionality.
49
We have been using theses method extensively through System.out
Serialization
The mechanism of storing the state of an object in the hard disk so
that it can be restored later by your program.
Serialization enables storing values of all instance variables which
includes both primitives and Serializable objects.
Serialization mechanism creates a file into which the state of the
object is written.
This file can later be read by the java program which can then
restore the object‟s state.
ObjectOutputStream and ObjectInputStream classes are
used for these purposes. They are wrapper classes that take
OutputStream and InputStream objects respectively
50
ObjectOutputStream &
ObjectInputStream
ObjectOutputStream
ObjectOutputStream(OutputStream out)throws
IOException
void writeXxx(xxx v) where xxx is any primitive type, or
Object
void write(int x)
And all the methods from OutputStream
ObjectInputStream
ObjectInputStream(InputStream in) throws
IOException
xxx readXxx() where xxx is any primitive type, or Object
int read()
And all the methods from InputStream 51
Steps to save and retrieve an object’s state
Saving an object state
1. FileOutputStream f= new
FileOutputStream(“MySerFile.ser”);
2. ObjectOutputStream obfile= new
ObjectOutputStream(f);
3. obfile.writeObject(objectInstance);
4. Obfile.close();
54
Example: Serialization
package general;
public abstract class Person
implements Serializable{
…
}
import java.io.*;
public class SerializeP {
public static void main(String str[]) throws
IOException{
Teacher f=new Teacher ("Tom");
55
//saving Teacher
ObjectOutputStream o=
new ObjectOutputStream(
new FileOutputStream("t.ser"));
o.writeObject(f);
o.close(); Could be any extension
59
Members of Properties
Properties()
Properties(Properties defaults)
void load(InputStream inStream) throws IOException
void load(Reader reader) throws IOException
Reads a key and element pairs from a character stream or byte stream.
Object setProperty(String key, String value
String getProperty(String key)
String getProperty(String key, String defaultValue)
setProperty()calls sets the key-value pair in the
getProperty() looks for the property with the specified key in this
property list. If the key is not found in this file, the default property list,
and its defaults, recursively, are then checked. The method returns null
in case of the 1st getProperty() method and defaultValue in
case of 2nd if the property is not found.
60
void store(OutputStream out, String comments) throws
IOException
void store(Writer writer, String comments) throws
IOException
Write the key-values pairs in the property list to the byte/character
stream.
61
Structure of a property file
Properties are processed in terms of lines. There are 2 types of line (as
specified by the API)
Natural line:
Line of characters terminated by \n or \r or \r\n
Example: blank line, comment line
Comment line begins within # or !
# This is a property file
Logical line:
Line that holds all the data of a key-element pair or
Multiple (natural) lines by escaping the line terminator sequence
with a backslash character \. Any white space at the start of
subsequent line is ignored. (example in next slide)
62
Key-Value pair in a logical line
The key contains all of the characters in the line starting with the first
non-white space character and up to, but not including, the first = or :
or blank spaces.
Examples of acceptable key-value pairs:
flowers rose
flowers:rose, lily
flowers:rose,lily
flowers : rose
flowers=rose
flowers = rose
flowers rose, lily, \
lotus, orchid
63
Example: Property file
import java.io.*;
import java.util.Properties;
System.out.println(props.getProperty("uname"));
System.out.println(props.getProperty("pwd"));
}catch(IOException ioe){ ioe.printStackTrace();}
finally{
try{ fileReader.close();
}catch(IOException ioe1){ }
} } 65
Result
66
Resource bundles
67
java.util.Locale
This class is used to represents a specific geographical, political, or
cultural region.
The date format, for instance are different in different regions. In India,
we have dd/mm/yyyy where as in US they follow mm/dd/yyyy.
Application must be locale sensitive when it displays data so that users
are comfortable.
Constructor
Locale(String language)
Locale(String language, String country)
Locale(String language, String country, String
variant)
Language argument should be ISO Language
Code(http://www.loc.gov/standards/iso639-2/englangn.html)
Country argument should be ISO Country
(http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-
lists/list-en1.html )
68
Members of Locale
Static constant that return local for many language and countries (some of
them are listed here)
static final Locale ENGLISH
static final Locale FRENCH
static final Locale GERMAN
static final Locale CHINESE
static final Locale JAPANESE
static final Locale US
static final Locale UK
static final Locale GERMANY
static final Locale CHINA
static final Locale JAPAN
Get methods like
String getCountry()
String getLanguage()
static Locale getDefault() which gets the current value of
the default locale for this instance of the Java Virtual Machine.
69
ResourceBundle
This is abstract class.
This class allows working with the resource bundle files with the help of
Locale class.
The resource bundle files are to be named in specific manner.
baseName + "_" + language1 + "_" + country1
baseName + "_" + language1
baseName
GreetResourceBundle.properties
GoodMorning=Good Morning
Goodbye=Good Bye
GreetResourceBundle_fr_FR.properties
GoodMorning=Bonjour
Goodbye=Au revoir
72
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.MissingResourceException;
public class ResBundle {
public static void main(String [] argv) {
try {
ResourceBundle rb1 =
ResourceBundle.getBundle("GreetResourceBundle");
System.out.println(rb1.getLocale());
System.out.println(rb1.getString("GoodMorning"));
System.out.println(rb1.getString("Goodbye"));
Locale frenchLocale = new Locale("fr", "FR");
ResourceBundle rb =
ResourceBundle.getBundle("GreetResourceBundle",
frenchLocale);
System.out.println(rb.getString("GoodMorning"));
System.out.println(rb.getString("Goodbye"));
} catch (MissingResourceException mre) {
mre.printStackTrace();73 } }}
RandomAccessFile
This class supports both reading and writing to a file simultaneously.
A file pointer is maintained which can be read by
the getFilePointer() method and set by the seek() method.
Constructor:
RandomAccessFile(File file, String mode)
Methods:
String readLine()
void writeBytes(String s)
XXX readXXX() where XXX represents all primitive type.
XXX writeXXX() where XXX represents all primitive type.
void seek(long pos)
long length()
74
long getFilePointer()
Modes
r: Open for reading only. Invoking any of the write methods of the
resulting object will cause an IOException to be thrown.
rw: Open for reading and writing. If the file does not already exist then
an attempt will be made to create it.
rws: Same as rw, and also require that every update to the file's
content or metadata be written synchronously to the underlying storage
device.
rwd: Same as rw, and also require that every update to the file's
content be written synchronously to the underlying storage device.
75
Example: RandomAccessFile
Code that replaces : by ;
import java.io.*;
public class Semi {
public static void main(String str[]) {
try {
File file = new File("Test1.java");
RandomAccessFile raf = new RandomAccessFile(file,"rw");
String s="";
long fp=raf.getFilePointer();
while((s= raf.readLine())!=null){
System.out.println("line: " +s);
if(s.contains(":")){
s= s.replace(':', ';');
raf.seek(fp);
raf.writeBytes(s); }
fp=raf.getFilePointer(); }
raf.close(); } catch (IOException e){
e.printStackTrace();} }}
76