IO Java Unit 2
IO Java Unit 2
5
System
• Java.lang package defines a class called System, which encapsulates
several aspects of the run-time environment.
• System also contains three predefined stream variables: in, out,
and err.
• These fields are declared as public, static, and final within System.
This means that they can be used by any other part of your
program and without reference to a specific System object.
• 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.
• However, these streams may be redirected to any compatible I/O
device.
Reading Console Input
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.
Buffered reader example
// 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
Here is a sample run:
do { Enter characters, 'q' to quit.
c = (char) br.read(); 123abcq
System.out.println(c); 1
} while(c != 'q'); 2
3
}
a
} b
c
q
Reading strings
// 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"));
}
}
Writing Console Output
• Here is a short example that uses write( ) to output the
character "A" followed by a newline to the screen:
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
PrintWriter
• PrintWriter is one of the character-based
classes.
• Using a character-based class for console
output makes internationalizing your program
easier.
• PrintWriter defines several constructors. The
one we will use is shown here:
PrintWriter(OutputStream outputStream,
boolean flushingOn) True – flushing is done
automatically
False- flushing is not
automatic
PrintWriterDemo
// Demonstrate PrintWriter
import java.io.*;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7; Uses print() nad println() methods just like
System.in
pw.println(i);
double d = 4.5e-7;
pw.println(d);
The output from this program is shown here:
} This is a string
} -7
4.5E-7
Reading and Writing Files
• FileInputStream(String fileName) throws
FileNotFoundException
• FileOutputStream(String fileName) throws
FileNotFoundException
Reading and Writing Files
import java.io.*; try {
class ShowFile { do {
public static void main(String args[]) i = fin.read();
{ if(i != -1) System.out.print((char) i);
int i; } while(i != -1);
FileInputStream fin; } catch(IOException e) {
// First, confirm that a filename has been System.out.println("Error Reading File");
specified. }
if(args.length != 1) { // Close the file.
System.out.println("Usage: ShowFile try {
filename"); fin.close();
return; } catch(IOException e) {
} System.out.println("Error Closing File");
// Attempt to open the file. }
try { }
fin = new FileInputStream(args[0]); }
} catch(FileNotFoundException e) {
System.out.println("Cannot Open File");
return; java ShowFile TEST.TXT
}
// At this point, the file is open and can be
read.
// The following reads characters until EOF is
encountered.
Single catch statement and closing of
file in finally -block
try {
fin = new FileInputStream(args[0]);
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(IOException e) {
System.out.println("I/O Error: " + e);
} finally {
// Close file in all cases.
try {
if(fin != null) fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}
Copy a File
import java.io.*; do {
class CopyFile { i = fin.read();
public static void main(String args[]) if(i != -1) fout.write(i);
throws IOException } while(i != -1);
{ } catch(IOException e) {
int i; System.out.println("I/O Error: " + e);
FileInputStream fin = null; } finally {
FileOutputStream fout = null; try {
// First, confirm that both files have been if(fin != null) fin.close();
specified. } catch(IOException e2) {
if(args.length != 2) { System.out.println("Error Closing Input
System.out.println("Usage: CopyFile from File");
to"); }
return; try {
} if(fout != null) fout.close();
// Copy a File. } catch(IOException e2) {
try { System.out.println("Error Closing Output
// Attempt to open the files. File");
fin = new FileInputStream(args[0]); }
fout = new FileOutputStream(args[1]); }
}
}
Automatically Closing a File
try (resource-specification) {
// use the resource
}
Automatically closing a file
import java.io.*;
class ShowFile {
public static void main(String args[])
{
int i;
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
try(FileInputStream fin = new FileInputStream(args[0])) {
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(FileNotFoundException e) {
System.out.println("File Not Found.");
} catch(IOException e) {
System.out.println("An I/O Error Occurred");
}
}
}
File class
• File(String directoryPath)
• File(String directoryPath, String filename)
• File(File dirObj, String filename)
The NIO system is built on two foundational items: buffers and channels. A buffer holds
data. A channel represents an open connection to an I/O device, such as a file or a socket.
In general, to use the NIO system, you obtain a channel to an I/O device and a buffer to
hold data
IO Vs NIO
• IO – Stream oriented means - read one or more
bytes at a time, from a stream
• Not cached
• Cannot move back and forth in the data