CSC 1214: Object-Oriented Programming
J. Kizito
Makerere University
e-mail: [email protected]: http://serval.ug/~jona
materials: http://serval.ug/~jona/materials/CSC1214
e-learning environment: http://muele.mak.ac.ug
office: block A, level 3, department of computer sciencealt. office: institute of open, distance, and eLearning, room 2
Java Input/Output (I/O)
Kizito (Makerere University) CSC 1214 April, 2018 1 / 22
Overview
1 Java I/OI/O StreamsPredefined StreamsConsole I/OFile I/O
Kizito (Makerere University) CSC 1214 April, 2018 2 / 22
Java I/O
Java I/OIntroduction
Apart from print() and println(), none of the I/O methods havebeen used significantly because most real applications of Java are nottext-based, console programs
Java provides strong, flexible support for I/O as it relates to files andnetworks
Java programs perform I/O through streams
Kizito (Makerere University) CSC 1214 April, 2018 3 / 22
Java I/O I/O Streams
Java I/OI/O Streams
A stream is an abstraction that either produces or consumesinformation
A stream is linked to a physical device by the Java I/O system
An input stream can abstract many different kinds of input: disk file,keyboard, network socket
An output stream may refer to the console, disk file, or networkconnection
Java implements streams within class hierarchies defined in thejava.io package
Kizito (Makerere University) CSC 1214 April, 2018 4 / 22
Java I/O I/O Streams
Java I/OByte streams and Character streams
Java 2 defines two types of classes: byte and character
Byte streams provide a convenient means for handling input and output of bytes
Character streams provide a convenient means for handling input and output ofcharacters
In some cases, character streams are more efficient than byte streams
The Byte Stream
Defined by using two classhierarchies
At the top are two abstract classes:InputStream and OutputStream
These classes define several keymethods including read() andwrite(), which, respectively, readand write bytes of data
The Character Stream
Defined by using two classhierarchies
At the top are two abstract classes:Reader and Writer
These classes define several keymethods including read() andwrite(), which read and writecharacters of data, respectively
Kizito (Makerere University) CSC 1214 April, 2018 5 / 22
Java I/O I/O Streams
java.io
Kizito (Makerere University) CSC 1214 April, 2018 6 / 22
Java I/O I/O Streams
The Byte Stream Classes
BufferedInputStream
BufferedOutputStream
ByteArrayInputStream Reads from a byte arrayByteArrayOutputStream Writes to a byte arrayDataInputStream Reading Java standard data typesDataOutputStream Writing Java standard data typesFileInputStream Reads from a fileFileOutputStream Writes to a fileFilterInputStream Implements InputStream
FilterOutputStream Implements OutputStream
InputStream Abstract classOutputStream Abstract classPipedInputStream Input pipePipedOutputStream Ouyput pipePrintStream Contains print() and println()
PushBackInputStream Supports one-byte “unget” – returns a byte to the inputstream
RandomAccessFile Random access file I/OSequenceInputStream Combination of two or more input streams that will be
read sequentiallyKizito (Makerere University) CSC 1214 April, 2018 7 / 22
Java I/O I/O Streams
java.io.InputStream
Kizito (Makerere University) CSC 1214 April, 2018 8 / 22
Java I/O I/O Streams
The Character Stream Classes
BufferedReader Buffered input character streamBufferedWriter Buffered output character streamCharArrayReader Reads from a character arrayCharArrayWriter Writes to a character arrayFileReader Reads from a fileFileWriter Writes to a fileFilterReader Filtered readerFilterWriter Filtered writerInputStreamReader Translates bytes to charactersLineNumberReader Counts linesOutputStreamWriter Translates characters to bytesPipedReader Input pipePipedWriter Output pipePrintWriter Contains print() and println()
PushBackReader Allows characters to be returned to the input streamReader Abstract classStringReader Reads from a stringStringWriter Writes to a stringWriter Abstract class
Kizito (Makerere University) CSC 1214 April, 2018 9 / 22
Java I/O I/O Streams
java.io.Reader
Kizito (Makerere University) CSC 1214 April, 2018 10 / 22
Java I/O Predefined Streams
Java I/OPredefined Streams
The java.lang package defines a class called System which containsthree predefined stream variables: in, out, and err
They are defined as public and static so they can be used by anyother part of your program without reference to a specific Systemobject
System.out refers to the standard output stream (default: console)
System.err refers to the standard error stream (default: console)
These streams may be redirected to any compatible I/O devices
System.in is an object of type InputStream; System.out andSystem.err are objects of type PrintStream
We have seen sample uses of System.out in previous examples
We have also seen a Console class that makes use of System.in
Kizito (Makerere University) CSC 1214 April, 2018 11 / 22
Java I/O Predefined Streams
Predefined Streamsjava.util.Scanner
Declaration
public final class Scanner
extends Object implements Iterator<String>, Closeable
Constructors
1 Scanner(File source)
2 Scanner(File source, String charsetName)
3 Scanner(InputStream source)
4 Scanner(InputStream source, String charsetName)
5 Scanner(Readable source)
6 Scanner(ReadableByteChannel source)
7 Scanner(ReadableByteChannel source, String charsetName)
8 Scanner(String source)
Kizito (Makerere University) CSC 1214 April, 2018 12 / 22
Java I/O Predefined Streams
Predefined Streamsjava.util.Scanner methods
Defines over 50 methods
nextX() methods:
1 String next()
2 String next(Pattern pattern)
3 String next(String pattern)
4 BigDecimal nextBigDecimal()
5 BigInteger nextBigInteger()
6 BigInteger
nextBigInteger(int radix)
7 boolean nextBoolean()
8 byte nextByte()
9 byte nextByte(int radix)
10 double nextDouble()
11 float nextFloat()
12 int nextInt()
13 int nextInt(int radix)
14 String nextLine()
15 long nextLong()
16 long nextLong(int rad)
17 short nextShort()
18 short
nextShort(int radix)Kizito (Makerere University) CSC 1214 April, 2018 13 / 22
Java I/O Console I/O
Java I/OReading Console Input
To obtain a stream that is attached to the console, we use thefollowing constructor:BufferedReader(Reader iReader)
For exampleBufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
In this case, br is a character-based stream that is linked to theconsole through System.in
Kizito (Makerere University) CSC 1214 April, 2018 14 / 22
Java I/O Console I/O
Reading Console InputBufferedReader Example
1. import java.io.*;
2.3. class BRRead {4. public static void main(String args[])
5. throws IOException {6. char c;
7. InputStreamReader sr = new InputStreamReader(System.in);
8. BufferedReader br = new BufferedReader(sr);
9. System.out.println("Enter characters, ’q’ to quit.");
10. // read characters11. do {12. c = (char) br.read();
13. System.out.println(c);
14. } while(c != ’q’);
15. }16. }
Sample output
Enter characters, ’q’ to quit.
12abcq
1
2
a
b
c
q
Kizito (Makerere University) CSC 1214 April, 2018 15 / 22
Java I/O Console I/O
Reading Console InputBufferedReader Example
1. import java.io.*;
2.3. class BRRead {4. public static void main(String args[])
5. throws IOException {6. char c;
7. InputStreamReader sr = new InputStreamReader(System.in);
8. BufferedReader br = new BufferedReader(sr);
9. System.out.println("Enter characters, ’q’ to quit.");
10. // read characters11. do {12. c = (char) br.read();
13. System.out.println(c);
14. } while(c != ’q’);
15. }16. }
Sample output
Enter characters, ’q’ to quit.
12abcq
1
2
a
b
c
q
Kizito (Makerere University) CSC 1214 April, 2018 15 / 22
Java I/O Console I/O
Reading Console InputReading Characters and Strings
Reading characters
To read a character from BufferedReader, use read():int read() throws IOException
read() reads a character from the input stream and returns it as aninteger value. -1 when the end of stream is encountered
Reading strings
To read a string, use the version of readLine() that is a member ofthe BufferedReader class:String readLine() throws IOException
For exampleBufferedReader br = new BufferedReder(
new InputStreamReader(System.in));
String str = br.readLine();
Kizito (Makerere University) CSC 1214 April, 2018 16 / 22
Java I/O Console I/O
Java I/OWriting Console Output
Use methods print(), println(), and write() defined byPrintStream (a type of object referenced by System.out)
Example:class WriteDemo {
public static void main(String args[]) {int b = ’A’;
System.out.write(b);
System.out.write(’\n’);System.out.println("A string");
}}
Kizito (Makerere University) CSC 1214 April, 2018 17 / 22
Java I/O Console I/O
Java I/OThe PrintWriter class
PrintWriter defines several constructors. E.g.,PrintWriter(OutputStream os, boolean flushOnNewline)
flushOnNewline controls whether Java flushes the output stream every time anew line (’\n’) character is output
PrintWriter supports the print() and println() methods
PrintWriter Example
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;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}}
Output
This is a string
-7
4.5E-7
Kizito (Makerere University) CSC 1214 April, 2018 18 / 22
Java I/O Console I/O
Java I/OThe PrintWriter class
PrintWriter defines several constructors. E.g.,PrintWriter(OutputStream os, boolean flushOnNewline)
flushOnNewline controls whether Java flushes the output stream every time anew line (’\n’) character is output
PrintWriter supports the print() and println() methods
PrintWriter Example
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;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}}
Output
This is a string
-7
4.5E-7
Kizito (Makerere University) CSC 1214 April, 2018 18 / 22
Java I/O Console I/O
Java I/OThe PrintWriter class
PrintWriter defines several constructors. E.g.,PrintWriter(OutputStream os, boolean flushOnNewline)
flushOnNewline controls whether Java flushes the output stream every time anew line (’\n’) character is output
PrintWriter supports the print() and println() methods
PrintWriter Example
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;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}}
Output
This is a string
-7
4.5E-7
Kizito (Makerere University) CSC 1214 April, 2018 18 / 22
Java I/O File I/O
Java I/OReading and Writing Files
Two of the most often-used streams are:1 FileInputStream(String filename) throws
FileNotFoundException2 FileOutputStream(String filename) throws
FileNotFoundException
When done with a file, close it using close() defined by bothFileInputStream and FileOutputStream
To read, use read() defined by FileInputStream
To write, use write() defined by FileOutputStream
Kizito (Makerere University) CSC 1214 April, 2018 19 / 22
Java I/O File I/O
Reading Example
1. import java.io.*;
2.3. class ShowFile {4. public static void main(String args[]) throws IOException {5. int i;
6. FileInputStream fin;
7.8. try {9. fin = new FileInputStream(args[0]);
10. } catch(FileNotFoundException e) {11. System.out.println("File Not Found");
12. return;
13. } catch(ArrayIndexOutOfBoundsException e) {14. System.out.println("Usage: ShowFile File");
15. return;
16. }17. do { // read characters until EOF is encountered18. i = fin.read();
19. if(i != -1) System.out.print((char) i);
20. } while(i != -1);
21. fin.close();
22. }23. }
Kizito (Makerere University) CSC 1214 April, 2018 20 / 22
Java I/O File I/O
Reading and Writing (Copy) Example
1. import java.io.*;
2. class CopyFile {3. public static void main(String args[]) throws IOException {4. int i;
5. FileInputStream fin;
6. FileOutputStream fout;
7. try {8. try { fin = new FileInputStream(args[0]); // open input file9. } catch(FileNotFoundException e) {10. System.out.println("Input File Not Found");
11. return;
12. }13. try { fout = new FileOutputStream(args[1]); } // open output file14. catch(FileNotFoundException e) {15. System.out.println("Error Opening Output File");
16. return;
17. }18. } catch(ArrayIndexOutOfBoundsException e) {19. System.out.println("Usage: CopyFile From To");
20. return;
21. }22. try { // Copy File23. do {24. i = fin.read();
25. if(i != -1) fout.write(i);
26. } while(i != -1);
27. } catch(IOException e) { System.out.println("File Error"); }28. fin.close();
29. fout.close();
30. }31. }
Kizito (Makerere University) CSC 1214 April, 2018 21 / 22
Java I/O File I/O
Modify File Contents
1. import java.util.*;
2. import java.io.*;
3.4. class FileReplace {5. public static void main(String args[]) {6. ArrayList<String> lines = new ArrayList<String>();
7. try {8. File f = new File(args[0]);
9. BufferedReader br = new BufferedReader(new FileReader(f));
10. for (String line; (line = br.readLine()) != null; ) {11. if (line.contains("Java")) // line to modify12. line = line.replace("Java", "C");
13. lines.add(line);
14. }15. br.close();
16.17. PrintStream ps = new PrintStream(f); // open for writing18. for (Iterator i = lines.iterator(); i.hasNext(); )
19. ps.println(i.next());
20. ps.close();
21. } catch (Exception ex) { ex.printStackTrace(); }22. }23. }
Kizito (Makerere University) CSC 1214 April, 2018 22 / 22
Top Related