CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: www: materials: e-learning environment: office: alt. office: jkizito@cis.mak.ac.ug http://serval.ug/~jona http://serval.ug/~jona/materials/csc1214 http://muele.mak.ac.ug block A, level 3, wing B, rm 304B institute of open, distance, and elearning, rm D20 Java Input/Output (I/O) Kizito (Makerere University) CSC 1214 May, 2017 1 / 22
Overview 1 Java I/O I/O Streams Predefined Streams Console I/O File I/O Kizito (Makerere University) CSC 1214 May, 2017 2 / 22
Java I/O Introduction Apart from print() and println(), none of the I/O methods have been used significantly because most real applications of Java are not text-based, console programs Java provides strong, flexible support for I/O as it relates to files and networks Java programs perform I/O through streams Kizito (Makerere University) CSC 1214 May, 2017 3 / 22
I/O Streams Java I/O I/O 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: disk file, keyboard, network socket An output stream may refer to the console, disk file, or network connection Java implements streams within class hierarchies defined in the java.io package Kizito (Makerere University) CSC 1214 May, 2017 4 / 22
I/O Streams Java I/O Byte 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 of characters In some cases, character streams are more efficient than byte streams The Byte Stream Defined by using two class hierarchies At the top are two abstract classes: InputStream and OutputStream These classes define several key methods including read() and write(), which, respectively, read and write bytes of data The Character Stream Defined by using two class hierarchies At the top are two abstract classes: Reader and Writer These classes define several key methods including read() and write(), which read and write characters of data, respectively Kizito (Makerere University) CSC 1214 May, 2017 5 / 22
I/O Streams java.io Kizito (Makerere University) CSC 1214 May, 2017 6 / 22
I/O Streams BufferedInputStream BufferedOutputStream ByteArrayInputStream ByteArrayOutputStream DataInputStream DataOutputStream FileInputStream FileOutputStream FilterInputStream FilterOutputStream InputStream OutputStream PipedInputStream PipedOutputStream PrintStream PushBackInputStream RandomAccessFile SequenceInputStream The Byte Stream Classes Reads from a byte array Writes to a byte array Reading Java standard data types Writing Java standard data types Reads from a file Writes to a file Implements InputStream Implements OutputStream Abstract class Abstract class Input pipe Ouyput pipe Contains print() and println() Supports one-byte unget returns a byte to the input stream Random access file I/O Combination of two or more input streams that will be read sequentially Kizito (Makerere University) CSC 1214 May, 2017 7 / 22
I/O Streams java.io.inputstream Kizito (Makerere University) CSC 1214 May, 2017 8 / 22
I/O Streams The Character Stream Classes BufferedReader BufferedWriter CharArrayReader CharArrayWriter FileReader FileWriter FilterReader FilterWriter InputStreamReader LineNumberReader OutputStreamWriter PipedReader PipedWriter PrintWriter PushBackReader Reader StringReader StringWriter Writer Buffered input character stream Buffered output character stream Reads from a character array Writes to a character array Reads from a file Writes to a file Filtered reader Filtered writer Translates bytes to characters Counts lines Translates characters to bytes Input pipe Output pipe Contains print() and println() Allows characters to be returned to the input stream Abstract class Reads from a string Writes to a string Abstract class Kizito (Makerere University) CSC 1214 May, 2017 9 / 22
I/O Streams java.io.reader Kizito (Makerere University) CSC 1214 May, 2017 10 / 22
Predefined Streams Java I/O Predefined Streams The java.lang package defines a class called System which contains three predefined stream variables: in, out, and err They are defined as public and static so they can be used by any other part of your program without reference to a specific System object 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 and System.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 May, 2017 11 / 22
Predefined Streams Predefined Streams java.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 May, 2017 12 / 22
Predefined Streams Predefined Streams java.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 May, 2017 13 / 22
Console I/O Java I/O Reading Console Input To obtain a stream that is attached to the console, we use the following constructor: BufferedReader(Reader ireader) For example BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); In this case, br is a character-based stream that is linked to the console through System.in Kizito (Makerere University) CSC 1214 May, 2017 14 / 22
Console I/O Reading Console Input BufferedReader 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 characters 11. 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 May, 2017 15 / 22
Console I/O Reading Console Input BufferedReader 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 characters 11. 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 May, 2017 15 / 22
Console I/O Reading characters Reading Console Input Reading Characters and Strings To read a character from BufferedReader, use read(): int read() throws IOException read() reads a character from the input stream and returns it as an integer value. -1 when the end of stream is encountered Reading strings To read a string, use the version of readline() that is a member of the BufferedReader class: String readline() throws IOException For example BufferedReader br = new BufferedReder( new InputStreamReader(System.in)); String str = br.readline(); Kizito (Makerere University) CSC 1214 May, 2017 16 / 22
Console I/O Java I/O Writing Console Output Use methods print(), println(), and write() defined by PrintStream (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 May, 2017 17 / 22
Console I/O Java I/O The PrintWriter class PrintWriter defines several constructors. E.g., PrintWriter(OutputStream os, boolean flushonnewline) flushonnewline controls whether Java flushes the output stream every time a new 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 May, 2017 18 / 22
Console I/O Java I/O The PrintWriter class PrintWriter defines several constructors. E.g., PrintWriter(OutputStream os, boolean flushonnewline) flushonnewline controls whether Java flushes the output stream every time a new 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 May, 2017 18 / 22
Console I/O Java I/O The PrintWriter class PrintWriter defines several constructors. E.g., PrintWriter(OutputStream os, boolean flushonnewline) flushonnewline controls whether Java flushes the output stream every time a new 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 May, 2017 18 / 22
File I/O Java I/O Reading and Writing Files Two of the most often-used streams are: 1 FileInputStream(String filename) throws FileNotFoundException 2 FileOutputStream(String filename) throws FileNotFoundException When done with a file, close it using close() defined by both FileInputStream and FileOutputStream To read, use read() defined by FileInputStream To write, use write() defined by FileOutputStream Kizito (Makerere University) CSC 1214 May, 2017 19 / 22
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 encountered 18. 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 May, 2017 20 / 22
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 file 9. } catch(filenotfoundexception e) { 10. System.out.println("Input File Not Found"); 11. return; 12. } 13. try { fout = new FileOutputStream(args[1]); } // open output file 14. 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 File 23. 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 May, 2017 21 / 22
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 modify 12. line = line.replace("java", "C"); 13. lines.add(line); 14. } 15. br.close(); 16. 17. PrintStream ps = new PrintStream(f); // open for writing 18. 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 May, 2017 22 / 22