0% found this document useful (0 votes)
13 views27 pages

IO Stream 11

Class note java

Uploaded by

2247018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views27 pages

IO Stream 11

Class note java

Uploaded by

2247018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Input and Output

in
Java

1
Introduction
➢The java.io package contains classes that perform input and
output.
➢ In Java, I/O classes are differentiated according to the type of
data being read or written.
➢ Byte oriented and numeric data is written with output streams
and read with input streams.
➢Character data, that is text, is written with writers and read
with readers.

2
Introduction (cont…)
➢ Readers and Writers operate much like streams but understand how to
convert to and from various external character sets like Big-5 Chinese or
MacRoman into Unicode.
➢ Whether you use streams or readers and writers depends on the type of
data you're dealing with.
➢ The two main stream classes are java.io.InputStream and
java.io.OutputStream.
➢ The two main reader and writer classes are java.io.Reader and
java.io.Writer
➢ These are abstract base classes for many different subclasses with more
specialized abilities.

3
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.
➢ An input stream can abstract many different kinds of input: from a disk file,
a keyboard, or a network socket.
➢ Likewise, an output stream may refer to the console, a disk file, or a
network connection.
➢ Streams are a clean way to deal with input/output without having every
part of your code understand the difference between a keyboard and a
network, for example.
➢ Java implements streams within class hierarchies defined in the java.io
package
4
Reading information into a program(input stream)

5
Writing information from a
program(output stream)

6
Byte Streams and Character Streams
➢ Java 2 defines two types of streams: byte and character.
➢ Byte streams provide a convenient means for handling input and output of
bytes.
➢ Byte streams are used, when reading or writing binary data.
➢ Character streams provide a convenient means for handling input and
output of characters.
➢ They use Unicode and, therefore, can be internationalized.
➢ Also, in some cases, character streams are more efficient than byte
streams.
➢ One other point: at the lowest level, all I/O is still byte-oriented.

7
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.
➢ 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.
➢ They are overridden by derived stream classes. 8
The Character Stream Classes

➢ Character streams are defined by using two class hierarchies.


➢ At the top are two abstract classes, Reader and Writer.
➢ 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.

9
The Predefined Streams
➢ All Java programs automatically import the java.lang package.
➢ This 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 and static 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.in is an object of type InputStream; System.out and System.err are
objects of type PrintStream.
10
Reading Console Input
➢ In Java, console input 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.
➢ BuffereredReader supports a buffered input stream. Its most commonly used
constructor is shown here:
BufferedReader(Reader inputReader)
➢ Here, 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.

11
Reading Console Input (Cont…)

➢ To obtain an InputStreamReader object that is linked to System.in, use the following


constructor:
InputStreamReader(InputStream inputStream)
➢ Because System.in refers to an object of type InputStream, it can be used for
inputStream.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

12
Reading Console Input (Cont…)
1. // Use a BufferedReader to read characters from the console.
2. import java.io.*;
3. class BRRead {
Output:
4. public static void main(String args[]) throws IOException
Enter characters, 'q' to
5. { quit.
6. char c;
123abcq
7. BufferedReader br = new
1
8. BufferedReader(new InputStreamReader(System.in));
9. System.out.println("Enter characters, 'q' to quit."); 2

10. // read characters 3


11. do { a
12. c = (char) br.read(); b
13. System.out.println(c); c
14. } while(c != 'q'); q
15. }
16. }
13
Reading Console Input (Cont…)
1. // Use a BufferedReader to read characters from the console.
2. import java.io.*;
3. class BRRead {
Output:
4. public static void main(String args[]) throws IOException
Enter characters, 'q' to
5. { quit.
6. char c;
123abcq
7. BufferedReader br = new
1
8. BufferedReader(new InputStreamReader(System.in));
9. System.out.println("Enter characters, 'q' to quit."); 2

10. // read characters 3


11. do { a
12. c = (char) br.read(); b
13. System.out.println(c); c
14. } while(c != 'q'); q
15. }
16. }
14
➢ This output may look a little different from what you expected,
because System.in is line buffered, by default.
➢ This means that no input is actually passed to the program until
you press ENTER. As you can guess, this does not make read( )
particularly valuable for interactive, console input

15
Reading Strings
1. // Read a string from console using a BufferedReader.
2. import java.io.*;
3. class BRReadLines {
4. public static void main(String args[]) throws IOException
5. {
6. // create a BufferedReader using System.in
7. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8. String str;
9. System.out.println("Enter lines of text.");
10. System.out.println("Enter 'stop' to quit.");
11. do {
12. str = br.readLine();
13. System.out.println(str);
14. } while(!str.equals("stop"));
15. }
16. } 16
Writing Console Output
➢ Console output is most easily accomplished with print( ) and println( ).
➢ 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.

17
Writing Console Output (cont…)
1. // Demonstrate System.out.write().
2. class WriteDemo {
3. public static void main(String args[]) {
4. int b;
5. b = 'A';
6. System.out.write(b);
7. System.out.write('\n');
8. }
9. }

18
The PrintWriter Class
➢ Although using System.out to write to the console is still permissible
under Java, its use is recommended mostly for debugging purposes or
for sample programs
➢ For real-world programs, the recommended method of writing to the
console when using Java is through a PrintWriter stream.
➢ PrintWriter is one of the character-based classes. Using a character-
based class for console output makes it easier to internationalize your
program.
➢ PrintWriter defines several constructors.
➢ PrintWriter pw = new PrintWriter(System.out, true);

19
The PrintWriter Class
1. // Demonstrate PrintWriter
2. import java.io.*;
3. public class PrintWriterDemo {
4. public static void main(String args[]) {
5. PrintWriter pw = new PrintWriter(System.out, true);
6. pw.println("This is a string");
7. int i = -7;
8. pw.println(i);
9. double d = 4.5e-7;
10. pw.println(d);
11. }
12. }

20
Reading and Writing Files
➢In Java, all files are byte-oriented, and Java provides
methods to read and write bytes from and to a file.
➢Two of the most often-used stream classes are
FileInputStream and FileOutputStream, which create byte
streams linked to files.
➢To open a file, you simply create an object of one of these
classes, specifying the name of the file as an argument to the
constructor.

21
Reading and Writing Files (Cont…)
➢While both classes support additional, overridden
constructors, the following are the forms that we will be
using:

FileInputStream(String fileName) throws FileNotFoundException


FileOutputStream(String fileName) throws FileNotFoundException

22
Reading and Writing Files (Cont…)
➢ When you are done with a file, you should close it by calling close( ).
➢ It is defined by both FileInputStream and FileOutputStream, as shown
here:
void close( ) throws IOException
➢ To read from a file, you can use a version of read( ) that is defined within
FileInputStream. The one that we will use is shown here:
int read( ) throws IOException

23
Reading and Writing Files (cont…)
1. import java.io.*; 13. catch(ArrayIndexOutOfBoundsException e) {
2. class ShowFile { 14. System.out.println("Usage: ShowFile File");
3. public static void main(String args[]) 15. return;
4. throws IOException 16. }
5. { 17. // read characters until EOF is encountered
6. int i; 18. do {
7. FileInputStream fin; 19. i = fin.read();
8. try { 20. if(i != -1) System.out.print((char) i);
9. fin = new FileInputStream(args[0]); 21. } while(i != -1);
10. } catch(FileNotFoundException e) { 22. fin.close();
11. System.out.println("File Not Found"); 23. }
12. return; 24. }
13. }

24
Reading and Writing Files (cont…)
➢ To write to a file, you will use the write() method defined by
FileOutputStream.
➢ Its simplest form is shown here:
➢void write(int byteval) throws IOException

25
Reading and Writing Files (cont…)
1. //java CopyFile FIRST.TXT SECOND.TXT 18. // open output file
19. try {
2. import java.io.*;
20. fout = new FileOutputStream(args[1]);
3. class CopyFile {
4. public static void main(String args[]) 21. } catch(FileNotFoundException e) {
5. throws IOException 22. System.out.println("Error Opening Output File");
6. { 23. return;
7. int i;
24. }
8. FileInputStream fin;
9. FileOutputStream fout; 25. } catch(ArrayIndexOutOfBoundsException e) {
10. try { 26. System.out.println("Usage: CopyFile From To");
11. // open input file 27. return;
12. try {
28. }
13. fin = new FileInputStream(args[0]);
14. } catch(FileNotFoundException e) {
15. System.out.println("Input File Not Found");
16. return;
17. }

26
Reading and Writing Files (cont…)
29. // Copy File
30. try {
31. do {
32. i = fin.read();
33. if(i != -1)
34. fout.write(i);
35. } while(i != -1);
36. } catch(IOException e) {
37. System.out.println("File Error");
38. }
39. fin.close();
40. fout.close();
41. }
42. } 27

You might also like