Download 08 - GEOCITIES.ws

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Unit 8 (Basic Input/Output)
Content
A) Using files in Java
B) Exception Handling
C) Filter Stream
D) The Standard Input & Output
1
A) Using files in Java
 The Java programming language provides no built-in
facility for manipulating files. But the Java standard
software library that comes with the JRE provides the
necessary classes for performing such operations.
 Most classes for performing I/O are in the java.io
package. Hence you need to import it at the beginning
of the source file
import java.io.*;
2
File Object
 Creating and using file objects: java.io.File class
The File class enables you to get information/attributes
about a file/directory
 we cannot get access to the content/data of a file via a
File object. It is not for that purpose!
 Note that creating a File object will NOT create a
physical file in your system.
 The most common constructors for a File object:
public File (String pathname)
public File (String parent, String child)
public File (File parent, String child)
// full pathname of file
// directory path + filename
// directory object + filename
3
 eg
File myfile = new File (“file1”);
File myfile = new File (“c:\\file2.txt”);
// file1 in current directory
// file2 in c:\file2.txt
 Since the path separator in Windows is ‘\’, to prevent
from confusion with special character in Java, e.g. ‘\t’,
we add one more ‘\’ after ‘\’.
 Creating a File instance does not create it physically
on your computer drive. It can refer to a non-existing
file and you can use the exists( ) method to determine
whether the file exists or not.
4
 A File instance can also be associated to a directory:
File mydir = new File (“c:\\java\\MT201”); \\c:\java\MT201
 using the method list( ) to list the files in a directory
String [ ] filename = mydir.list( );
for (int j=0;j<filename.length;j++) {
System.out.println(filename[j]);
}
5
file/directory operation method
Method Name
Return Type
public boolean canRead( )
True if the file can be read, and false otherwise
public boolean canWrite( )
True if the file can be written, and false otherwise
public boolean exists( )
True if the file exists, and false otherwise
public boolean isDirectory( )
True if the name supplied to the constructor is referring
to a physical file, and false otherwise
public boolean isFile( )
True if the name supplied to the constructor is referring
to a physical file, and false otherwise
public boolean isHidden( )
True if the file is hidden, and false otherwise
public long lastModified( )
The time when the file is last modified and the time is
specified in number of seconds since 00:00:00 GMT,
Jan 1, 1970
public long length( )
The size of the file
6
Reading and writing files
 Reading a file can be viewed as a flow of data stream
from the outside world into the JVM - input stream /
source stream.
 Writing a file can be viewed as a flow of data stream
from the JVM to the outside world - output stream /
destination stream.
 In Java we can read / write data in units of 8-bit bytes
or 16-bit Unicode characters. They are known as
byte stream and character stream respectively
 Byte stream is used for (byte-oriented) binary files,
e.g. execution, image, audio, video files & etc
 Character stream is used for (character-based)
textual data, e.g. text files
7
Stream
 Performing reading and writing operations on a file can
be considered the flow of data between two entities.
 For reading operation, a flow of data from the outside
world into the JVM while for writing operation, a flow
of data from the JVM to the outside world.
Write / Output
Operation
Read / Input
Operation
Source
Stream
JVM
Destination
Stream
8
Table 8.4 different categories of stream classes
 there are byte mode and character mode operations
 1 byte = 8 bits
 1 character = 2 byte = 16 its
Byte stream
(1 byte = 8 bits)
Character stream
(1 char = 2 byte = 16 bits)
Input
Stream
InputStream
Output
stream
OutputStream
eg. FileOutputStream
Reader
eg. FileReader
Writer
eg. FileWriter
eg. FileInputStream
9
Byte Stream
 If an object supports a flow of data in units of byte,
then it is known as a byte stream
 it can be an input stream or output stream
 byte stream is usually to handle binary file
 The abstract class java.io.InputStream defines
general types of how an input byte stream should behave
 The abstract class java.io.OutputStream defines
general types of how an output byte stream should
behave
 However, we have to use concrete subclasses of these
abstract classes for us to manipulate a file
 FileInputStream
 FileOutputStream
10
FileOutputStream
 Hence the steps to write to a file:
1. create an object of FileOutputStream class
2. send the write( ) messages to the FOS object
3. send the close( ) message to the FOS object
 2 common ways to create a FileOutputStream object
 method-a
File outFile = new File(pathString);
OutputStream out = new FileOutputStream(outFile);
 method-b; one instruction is saved
OutputStream out = new FileOutputStream(pathString);
11
 Note that if the specified file already exists, creating an
output stream onto that file will overwrite it.
 So be careful and better check for file existence
before writing it (modify method-a).
 the write( ) method is overloaded in the OutputStream
class:
public void write(int b)
// int but not byte ?!
public void write(byte[] b)
public void write(byte[] b, int offset, int length) // length = no of bytes
12
example : FileOutputStream
import java.io.*;
public class TestFileOutput {
public static void main(String args[]) {
try {
File myfile = new File (args[0]);
FileOutputStream fs= new FileOutputStream (myfile);
for (int j=0; j<100; j++) {
fs.write(j);
}
fs.close( );
}
catch (Exception e) { }
}
}
13
Input Streams
 The concept behind performing a reading operation is similar to
the writing operation, but the direction of data flow is reversed.
 The abstract InputStream class defines overloaded read( )
methods and close( ) method.
 However if we want to read from a file, we must use of an object
from the concrete FileInputStream class which is a subclass
of the InputStream class
 steps to read from a file:
1. create an object of FileInputStream class
2. send the read( ) messages to the FIS object until all data have
been read from the source (indicated by a return value of -1
from the read( ) method)
3. send the close( ) message to the FIS object
14
 2 most common ways to create a FileInputStream object:
File inFile = new File(pathString);
InputStream fis = new FileInputStream(inFile);
// method-A
InputStream fis = new FileInputStream(pathString);
// method-B
 runtime error occurs, if the file to be read does not exist
 the read( ) method has been overloaded in the InputStream
class:
public int read( )
// the byte data read is returned as int
public int read(byte[] buf)
// no. of bytes read is returned
public int read(byte[] buf, int offset, int length)// no. of bytes read is returned
 Note that we could check whether we have read up to the
end of a file by the condition:
fis.read( ) == -1
15
example : FileInputStream
import java.io.*;
public class TestFileInput {
public static void main(String args[]) {
try {
FileInputStream fs = new FileInputStream (args[0]);
int i;
while ((i = fs.read( )) != -1) {
System.out.println(i);
}
fs.close( );
}
catch (Exception e) { }
}
}
16
Copying Data from InputStream to OutputStream
import java.io.*;
public class StreamCopier {
public static void main(String args[]) {
int i;
try {
FileInputStream ifs = new FileInputStream (args[0]);
File myfile = new File (args[1]);
FileOutputStream ofs = new FileOutputStream (myfile);
while ((i = ifs.read( )) != -1) { ofs.write(i); }
ifs.close( );
ofs.close( );
}
catch (Exception e) { }
}
}
17
Character Stream
 Character stream is the character-based stream.
 Every reading/writing operation handles the data in units
of char.
 It is usually used for handling textual data
 The input character stream is generally considered a
Reader object.
 The output character stream is considered a Writer
object.
 Reader and Writer are abstract classes defining the
common methods.
 we’ll use concrete classes, FileReader and
FileWriter for reading and writing files in units of
character
18
FileWriter
 2 most common ways to create a FileWriter object:
File outFile = new File(pathString);
Writer writer = new FileWriter(outFile);
// method-A
Writer writer = new FileWriter(pathString);
// method-B
 The overloaded write( ) method in the Writer class:
public void write(int c)
// note int but not char type
public void write(char[] c)
public void write(char[] c, int offset, int length)
public void write(String str)
public void write(String str, int offset, int length)
19
example : FileWriter
import java.io.*;
public class TestFileWriter {
public static void main(String args[]) {
try {
File myfile
= new File (args[0]);
FileWriter fw = new FileWriter (myfile);
fw.write(1);
fw.write("Hello");
fw.write('a');
fw.close( );
}
catch (Exception e) { }
}
}
20
FileReader
 the concept behind performing a reading operation is
similar to the writing operation, but the direction of data
flow is reversed.
 If we want to read from a file, we need to make use of
an object from the concrete FileReader class which is
a subclass of the Reader class.
 The steps to read from a file using an input character
stream is similar to that of using an input byte stream
 2 most common ways to create a FileReader object:
File inFile = new File(pathString);
Reader fr = new FileReader(inFile);
// method-A
Reader fr = new FileReader(pathString); // method-B
21
 The overloaded read( ) method in the Reader class:
public int read( )
// the char data read is returned as int
public int read(char[] buf)
// no. of chars read is returned
public int read(char[] buf, int offset, int length)
 Note that we could check whether we have read up to
the end of a file by the condition:
fr.read( ) == -1
22
FileReader
import java.io.*;
public class TestFileReader {
public static void main(String args[]) {
int j;
try {
File myfile = new File (args[0]);
FileReader fr = new FileReader (myfile);
while ( (j=fr.read( ) ) != -1) {
// read Char ‘j’
System.out.println ((char)j);
// casting
}
fr.close()
}
catch (Exception e) {}
}
}
23
B) Exception Handling
 An exception happens when a Java program performs an
illegal operation, such as performing a division
operation by zero at runtime.
 Exception may also occur when a FileInputStream
object refers to the non-existing file.
 The occurrence of an exception indicates
 a runtime error or
 problematic situation.
 The exception is generated to tell the program that such
a problem has happened and the program should
perform suitable remedial action to handle it.
24
Exception hierarchy
Throwable
Error
…
Exception
RuntimeException
ArithmeticException
…
…
IOException
FileNotFoundException
unchecked
checked
exceptions
exceptions
…
25
 there are 2 handling approaches
 throws
// control is passed to the caller
 try/ catch/ finally // to be resumed below the block
 eg
try {
// codes that cause a potential checked exception
} catch (Exception-class1 variable1) {
// codes to execute in case of exception1
} catch (Exception-class2 variable2) {
// codes to execute in case of exception2
} catch (…) {
...
} finally {
// codes to execute no matter whether there is or isn’t exception
}
public class approach$2 throws Exception {
--}
26
Try/Catch
 A program segment that can cause exceptions can be
handled by using the keywords try and catch, eg :
public class TestException {
public static void main(String args[]) {
int j=1;
int a = Integer.parseInt(args[0]);
try {
j = j / a;
// to be test for Division by zero
}
catch (ArithmeticException e) {
System.out.println(“error”);
}
}
}
27
 Multiple catch blocks are allowed in a program segment
to catch different exceptions.
 try/catch is required for some Java statements,
 eg. when defining InputStream object;
 otherwise compilation error occurs, eg.:
TestFileOutput.java:7: unreported exception
java.io.FileNotFoundException; must be caught or declared
to be thrown
FileOutputStream fs = new FileOutputStream (myfile);
28
 for multiple catch blocks, a checked exception is
matched sequentially with the exception types specified.
If the checked exception matches with the exception
class or any of its subclasses, the corresponding codes
inside the block is executed. Then execution is
transferred to the finally block (if any) and the codes
afterwards.
 the following example is a bad catch blocks design.
try {
// codes that cause a potential checked exception
} catch (IOException e) {
// codes to execute in case of IOException
} catch (FileNotFoundException e) {
// codes to execute in case of FileNotFoundException
}
29
Throwing Exception
pp 67~68
 Java allows a method that executes statements that may cause
exceptions not to handle the caused exception by itself,
 ie. no need to enclose those statements in a try/catch block.
 We can use ‘throw <exception-list>’ to stop running the
subsequent statements in the method and the flow of the control
will be returned to the caller method with the caused exception.
 When an exception is raised in a method that throws it, execution
in the method is terminated immediately and control is returned
to the caller.
 The caller (which is also inside a method) can again choose to
handle the exception or throw the exception to its own caller.
 Refer to the examples ByteStreamCopier.java and
FileStreamCopy.java again.
30
C) Filter Stream
 Java provides some classes that do not work on
particular storage media or communication channels, but
on the general input/output streams.
 The idea is like this:
Input filter
input byte stream objectinput stream filter objectdata in JVM
Output filter
data in JVMoutput stream filter objectoutput byte stream object
 Java provides many filter classes for different purposes.
The commonly used ones are for data conversion (e.g.
converting bytes read into characters, integers and
floating-point numbers), and improving performance
(i.e. data buffering).
31
Filter streams for conversion
 conversion between 8-bit byte and 16-bit character is the most
common
 Java handles characters in Unicode, which is a 16-bit coding
system. but, characters in a text file in your storage can be 8 bits
or 16 bits depending on the coding system of your platform (e.g.
in Chinese Windows characters are represented in 8-bit ASCII
code for English and 16-bit BIG5 code for Chinese).
 Hence the same character can have different representations
(codes) inside a text file on a particular platform and inside JVM.
 And this is where translation/conversion is required when reading
and writing character data between a data source and a data
destination with JVM.
char in data source  JVM (16-bit Unicode char)  char in data destination
32
 the Reader and Writer classes introduced earlier are
actually filter stream classes for data conversion.
 the FileReader object creation is actually a shorthand of:
InputStream in = new FileInputStream(file); // byte stream
Reader reader = new InputStreamReader(in); // character stream
 the FileWriter object creation is actually a shorthand of:
OutputStream out = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(out);
// byte stream
// character stream
 The conversion of an English letter from a text file (8-bit)
to JVM (16-bit Unicode character) is simple. An extra
byte filled with 0’s are added to the front of the 8-bit
letter to make it 16-bit.
 The reverse conversion of an English letter, i.e. from
JVM to text file, is also simple. The first byte of the
Unicode is taken away
33
 However, if the conversion involves other non-ASCII
characters (e.g. BIG5 Chinese character), we may have
to specify explicitly the coding system in the filter’s
constructors.
public InputStreamReader(InputStream in, String charsetName);
public OutputStreamWriter(OutputStream out, String charsetName);
 For example, you have a text file with Chinese BIG5
characters and you want to read it by a Java program
running on a non-BIG5 platform. You have to specify
the translation explicitly:
InputStream in = new FileInputStream(“myChineseFile.txt”);
Reader reader = new InputStreamReader(in, “BIG5”);
 Refer to Unit 8 P.105 for details.
34
Filter streams for buffering byte streams
 reading and writing on physical files are slower than on memory
 Instead of writing data byte-by-byte to physical file, it is better
to write data temporarily to memory first and then a large block
of data is transferred from memory to physical file. The
temporarily memory is known as buffer.
 The reverse is also true when reading data from physical file.
 Data are pre-read in block into memory and released byte-bybyte upon request.
 To achieve buffering transparently, we can make use of the
BufferedInputSream and BufferedOutputStream classes.
They are subclass of InputStream and OutputStream respectively.
 Refer to the example BufferedStreamCopy.java.
35
 Reading and writing files char-by-char are sometimes
not preferable for text files, as it is slow and also we
have to handle the line-break ourselves (which is
different on different platforms).
 Java provides some filter classes for us to read and write
text files line-by-line.
 We can wrap the BufferedReader object around the
FileReader object to buffer the input character stream.
The overloaded read( ) method reads a specified block
of characters into the buffer. In addition, the readLine( )
method reads one complete line and returns a string.
Reader reader = new FileReader(“myFile.txt”);
BufferedReader br = new BufferedReader(reader);
String lineRead = br.readLine( );
36
 Similarly we can wrap the BufferedWriter object around
the FileWriter object to buffer the output character stream.
 The overloaded write( ) method writes a specified block
of characters to the buffer
 You have to flush( ) the output stream explicitly to
ensure transfer of data from buffer to file.
 However the class does not provide any method to write
primitive data types as string to a text file.
 We hence usually wrap another class PrintWriter around
BufferedWriter to use the overloaded print( ) and
println( ) methods.
Writer writer = new FileWriter(“myFile.txt”);
BufferedWriter bw = new BufferedWriter(writer);
PrintWriter pw = new PrintWriter(bw);
pw.println(100); pw.println(“Hello”); pw.println(999.99);
37
D) The Standard Input & Output
 3 pre-defined standard I/O streams in java.lang.System :
 System.in standard input
 System.out standard output
 System.err standard error
 ‘in’, ‘out’ and ‘err’ are class variables of the class System.
 The class variable ‘in’ refers to InputStream object
 The class variable ‘out & ‘err’ refer to PrintStream objects
 When the JVM is launched, an InputStream object attached to
the computer keyboard is prepared and is referred by the class
variable ‘in’
 Two PrintStream objects are prepared and are made accessible
by class variables out and err
38
 Since the class variable ‘in’ refers to the InputStream
object that is attached to the keyboard and has the method
read( ), keyboard entry can be read using :
in . read( )
 To access the class variable ‘in’ and get the user inputs, we
can type:
System.in.read( )
 pp80 is an example of reading keystrokes from keyboard
until the Ctrl-Z or Ctrl-D is pressed.
 Since the class variable ‘err’ and ‘out’ refer to the
PrintStream object which has a method print and
method println, we can type:
System.out.print( ….)
System.err.print(…..)
System.out.println(….)
System.err.println(…..)
39