IO-JAVA_ver3

Download Report

Transcript IO-JAVA_ver3

I/O Basics
7 April 2016

Aside from print( ) and println( ), none of the I/O
methods have been used significantly. The reason is
simple: most real applications of Java are not text-based,
console programs.

they are graphically oriented programs that rely upon
Java’s Abstract Window Toolkit (AWT) for interaction
with the user.

Java’s support for console I/O is limited and somewhat
awkward to use — even in simple example programs.
Text-based console I/O is just not very important to Java
programming.
7 April 2016
2
Streams





Java programs perform I/O through streams.
A stream is an abstraction that either produces or consumes
information.
A stream is linked to a physical device by the Java I/O
system.
All streams behave in the same manner, even if the actual
physical devices to which they are linked differ.
Same I/O classes and methods can be applied to any type of
device.
7 April 2016
3
Streams(contd.)




Input stream can abstract many different kinds of input: from
a disk file, a keyboard, or a network socket.
Output stream may refer to the console, a disk file, or a
network connection.
Streams deal with input/output without having every part of
your code understand the difference between a keyboard
and a network.
Java implements streams within class hierarchies defined in
the java.io package.
7 April 2016
4
Byte Streams and Character Streams





Java 2 defines two types of streams: byte and character.
Byte streams provide means for handling input and output of
bytes and are used for reading or writing binary data.
Character streams handle input and output of characters.
They use Unicode and, therefore, can be internationalized.
In some cases, character streams are more efficient than
byte streams.
At the lowest level, all I/O is byte-oriented
7 April 2016
5
The Byte Stream Classes




Byte streams are defined by using two class hierarchies. At
the top are two abstract classes: InputStream and
OutputStream.
Each of these abstract classes has several concrete
subclasses, that handle the differences between various
devices, such as disk files, network connections, and even
memory buffers.
to use the stream classes, you must import java.io.
The abstract classes InputStream and OutputStream
define several key methods that the other stream classes
implement. Two of the most important are read() and write(),
which, respectively, read and write bytes of data. Both
methods are declared as abstract inside InputStream and
OutputStream.
7 April 2016
6

They are overridden by derived stream classes.
The Character Stream Classes


Character streams are defined by using two class
hierarchies.
At the top are two abstract classes, Reader and Writer,
which define several key methods that the other stream
classes implement.
7 April 2016
7






These abstract classes handle Unicode character streams.
Java has several concrete subclasses of each of these.
Two of the most important methods are read( ) and write( ),
which read and write characters of data, respectively.
These methods are overridden by derived stream classes
First slide is Byte Stream classes
Second slide is the character stream I/O classes
7 April 2016
8
7 April 2016
9
7 April 2016
10
The Predefined Streams





java.lang package defines a class called System, which
encapsulates several aspects of the run-time environment.
Using some of its methods, you can do the settings of various
properties associated with the system.
System also contains three predefined stream variables, in,
out, and err.
These fields are declared as public, static and final within
System.
They can be used by any other part of the program and
without reference to a specific System object.
7 April 2016
11







System.out refers to the standard output stream. By default,
this is the console.
System.in refers to standard input, which is the keyboard by
default.
System.err refers to the standard error stream, which also is
the console by default.
These streams may be redirected to any compatible I/O
device.
System.in is an object of type InputStream
System.out and System.err are objects of type
PrintStream.
These are byte streams, used to read and write characters
from and to the console.
7 April 2016
12
Reading Console Input




Console input is accomplished by reading from System.in.
To obtain character-based stream that is attached to the
console, you wrap System.in in a BufferedReader object.
BuffereredReader supports a buffered input stream.
Constructor is shown here:
 BufferedReader(Reader inputReader)
7 April 2016
13





inputReader is the stream that is linked to the instance of
BufferedReader that is being created.
Reader is an abstract class.
One of its concrete subclasses is InputStreamReader,
which converts bytes to characters.
To obtain an InputStreamReader object that is linked to
System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
7 April 2016
14




System.in refers to an object of type InputStream, it can be
used for inputStream.
The following line of code creates a BufferedReader that is
connected to the keyboard:
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
After this statement executes, br is a character-based
stream that is linked to the console through System.in.
7 April 2016
15
Reading Characters



To read a character from a BufferedReader, use read( ).
 int read( ) throws IOException
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. It
can throw an IOException.
7 April 2016
16
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException {
char c;
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);
} while(c != 'q');
}
}
7 April 2016
17
Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q
System.in is line buffered, by default. This means that
no input is actually passed to the program until you
press ENTER.
7 April 2016
18
Reading Strings



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
It returns a String object.
7 April 2016
19
//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 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
7 April 2016
20
import java.io.*; //A tiny Editor
class TinyEdit {
public static void main(String args[]) throws IOException {
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
for(int i=0; i<100; i++) {
str[i] = br.readLine();
if(str[i].equals("stop")) break;
}
7 April 2016
21
System.out.println("\nHere is your file:");
// display the lines
for(int i=0; i<100; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
}
}
}
7 April 2016
22
Here is a sample run:
Enter lines of text.
Enter 'stop' to quit.
This is line one.
This is line two.
Just create String objects.
stop
Here is your file:
This is line one.
This is line two.
Just create String objects
7 April 2016
23
Writing Console Output




PrintStream is an output stream derived from
OutputStream, it implements the low-level method write().
write() can be used to write to the console:
void write(int byteval)
This method writes to the stream the byte specified by
byteval.
byteval is declared as an integer, only the low-order eight
bits are written.
7 April 2016
24
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
Writes A to the console and adds a new line.
7 April 2016
25
Reading and Writing Files



In Java, all files are byte-oriented
FileInputStream and FileOutputStream create byte
streams linked to files
To open a file, create an object of one of these classes,
specifying the name of the file as an argument to the
constructor
FileInputStream (String fileName) throws
FileNotFoundException
FileOutputStream (String fileName) throws
FileNotFoundException
7 April 2016
26
For closing a file, void close() throws IOException
To read from a file, int read() throws IOException
reads a single byte from the file and returns it as an integer
/* Display a text file. Specify the name of the file that you want
to see. For example, to see a file called TEST.TXT, use the
following command line.
java ShowFile TEST.TXT */
import java.io.*;
class ShowFile {
public static void main(String args[]) throws IOException {
int i;
FileInputStream fin;
7 April 2016
27
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
// read characters until EOF is encountered
do {
i = fin.read( );
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close( );
}
}
7 April 2016
28
To write to a file, use write( ) method defined by
FileOutputStream.
void write(int byteval) throws IOException
Although byteval is declared as an integer, only the low-order
eight bits are written to the file
/* Copy a text file. To use this program, specify the name of the
source file and the destination file.
For example, to copy a file called FIRST.TXT to a file called
SECOND.TXT, use the following command line.
java CopyFile FIRST.TXT SECOND.TXT
*/
7 April 2016
29
import java.io.*;
class CopyFile {
public static void main(String args[]) throws IOException {
int i;
FileInputStream fin;
FileOutputStream fout;
try {
//open input file
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
}
7 April 2016
30
//open output file
try {
fout = new FileOutputStream(args[1]);
} catch(FileNotFoundException e) {
System.out.println("Error Opening Output File");
return;
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: CopyFile From To");
return;
}
7 April 2016
31
//Copy File
try {
do {
i = fin.read( );
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException e) {
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
7 April 2016
32
File




The File class does not operate on streams
It deals directly with files and the file system.
File class does not specify how information is retrieved from
or stored in files; it describes the properties of a file itself.
A File object is used to obtain or manipulate the information
associated with a disk file, such as the permissions, time,
date, and directory path, and to navigate subdirectory
hierarchies.
7 April 2016
33



A directory in Java is treated as a File with one additional
property—a list of filenames that can be examined by the
list( ) method.
The following constructors can be used to create File objects:
 File(String directoryPath)
 File(String directoryPath, String filename)
 File(File dirObj, String filename)
 File(URI uriObj)
Here, directoryPath is the path name of the file, filename is the
name of the file or subdirectory, dirObj is a File object that
specifies a directory, and uriObj is a URI object that describes a
file.
7 April 2016
34




The following example creates three files: f1, f2, and f3. The
first File object is constructed with a directory path as the only
argument. The second includes two arguments—the path and
the filename. The third includes the file path assigned to f1
and a filename; f3 refers to the same file as f2.
File f1 = new File("/");
File f2 = new File("/","autoexec.bat");
File f3 = new File(f1,"autoexec.bat");
import java.io.File;
// Demonstrate File
class FileDemo {
static void p(String s) {
System.out.println(s); }
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT");
p("File Name: " + f1.getName());
7 April 2016
35
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");
p(f1.canWrite() ? "is writeable" : "is not writeable");
p(f1.canRead() ? "is readable" : "is not readable");
p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
p(f1.isFile() ? "is normal file" : "might be a named pipe");
p(f1.isAbsolute() ? "is absolute" : "is not absolute");
p("File last modified: " + f1.lastModified());
p("File size: " + f1.length() + " Bytes");
}
}
7 April 2016
36
File Name: COPYRIGHT
Path: /java/COPYRIGHT
Abs Path: /java/COPYRIGHT
Parent: /java
exists
is writeable
is readable
is not a directory
is normal file
is absolute
File last modified: 812465204000
File size: 695 Bytes
7 April 2016
37



isFile() returns true if called on a file and false if called
on a directory.
Also isFile( ) returns false for some special files, such
as device drivers and named pipes, so this method can
be used to make sure the file will behave as a file.
The isAbsolute( ) method returns true if the file has an
absolute path and false if its path is relative.
7 April 2016
38
7 April 2016
39
7 April 2016
40
Directories
•A directory is a File that contains a list of other files and
directories.
•The isDirectory() method will return true when
you create a File object and it is a directory.
list() is called on the object to extract the list of
other files and directories present inside.


String[ ] list( )
The list of files is returned in an array of String
objects.
7 April 2016
41
// Using directories.
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();
7 April 2016
42
for (int i=0; i < s.length; i++) {
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");
}
}
}
7 April 2016
43
Here is sample output from the program.
Directory of /java
bin is a directory
lib is a directory
demo is a directory
COPYRIGHT is a file
README is a file
index.html is a file
include is a directory
src.zip is a file
hotjava is a directory
src is a directory
7 April 2016
44