Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

M.

El Dick 1

Input/Output
2

 I/O:keyboard, console, file, etc.


 Advantages of file I/O
 Permanent copy
 Output from one program can be input to another
 Input can be automated (rather than entered
manually)

I/O
Streams and files M. El Dick

The File Class


4

3 The File Class Package java.io


 Contains methods for obtaining file properties,
renaming and deleting files
 Does not contain methods for reading and
writing files

M. El Dick M. El Dick
The File Class
5

 Acts like a wrapper class for file names


 Refers to a file object or directory object

File file = new File ("primes.bin");


File directory = new File ("C:\\java");

M. El Dick 6 M. El Dick

Example Example: output


7 8

M. El Dick M. El Dick
Using Path Names
9

 UNIX :
 /user/smith/home.work/java/FileDemo.java
10 How to write/read?
 Windows :
 D:\Work\Java\Programs\FileDemo.java
 When a backslash is used in a quoted string it must be
written as two backslashes since backslash is the
escape character:
 "D:\\Work\\Java\\Programs\\FileDemo.java"

M. El Dick M. El Dick

How to do I/O Open the stream


11 12

 import java.io.*;  To connect to some external location (outside my


program)
 Open the stream  Done only once
 Use the stream (read, write, or both)
 Close the stream

 Note : IOException may occur during any I/O


operation

M. El Dick M. El Dick
Close the stream Stream
13 14

 To disconnect  A stream connects a program to an I/O object


 Rules:  Input stream: provides input to a program
 Limitednumber of streams open at one time  E.g. System.in
 connects a program to the keyboard
 No more than one stream open on the same file
 Output stream: accepts output from a program
 Close a stream before opening it again
 E.g. System.out
 connects a program to the screen

M. El Dick M. El Dick

Stream Buffering
15 16

 Can be:  Not buffered: reading/writing byte by byte


 Byte-oriented  “little” delay for each byte
 Use Streams  1 disk operation per byte---high overhead
 Character-oriented
 Use Reader and Writer (encoding scheme)  Buffered: reading/writing in “chunks”
 Some delay for some bytes
 1 disk operation per buffer of bytes---low overhead

M. El Dick M. El Dick
Java I/O classes The FileWriter Class
17 18

 Too many
 4 categories based on class suffix : Methods write(int character) write(char[] s) write(string s)
append (int character)
Byte Character flush()

Input InputStream Reader Construction File f = new File(filename);


FileWriter w = new FileWriter(f);
Output OutputStream Writer
FileWriter w = new FileWriter(filename);

M. El Dick M. El Dick

The BufferedWriter Class The PrintWriter Class


19 20

Methods write(int char) Methods print(char c)


write(char[] buf, int off, int len) print(string s)
write(string buf, int off, int len) print(int i)
newLine() print(double d)
flush() print(boolean b)
println(…)
Construction File f = new File(filename);
FileWriter w = new FileWriter(f); Construction File f = new File(filename);
BufferedWriter b = new BufferedWriter(w); PrintWriter w = new PrintWriter(f);
Or
PrintWriter w = new PrintWriter(new
BufferedWriter (new FileWriter(filename);
M. El Dick M. El Dick
Example Appending to a text File
21 22

import java.io.*;
public class CharacterFileOutput {
 To append at the end of an existing file:

public static void main (String args[]){ Boolean append = true;


FileWriter f = new FileWriter ("book.txt", append);
try {
FileWriter out = new FileWriter("File.txt"); 
System.out.println("Encoding:"+out.getEncoding());  Otherwise, file is overwritten (by default)
out.write("Info404 course");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
M. El Dick M. El Dick
}

The FileReader Class The BufferedReader Class


23 24

Methods int read() int read(char[] buffer) Methods int read()


int read(char[] cbuf, int offset, int length) int read(char[] cbuf, int offset, int length)
long skip(long n) String readLine()
long skip(long n)

Construction File f = new File(“filename”); Construction BufferedReader b = new BufferedReader(


FileReader w = new FileReader(f); new FileReader(“filename”));

FileReader w = new FileReader(“filename”);

M. El Dick M. El Dick
Example Console input
25 26

import java.io.*;
 To read input from the console, associate a stream with
public class CharacterFileInput {
the standard input System.in
public static void main (String args[]){
import java.io.*;
File f = new File("File.txt");
public class ConsoleInput {
char buffer[]; public static void main (String args[]){
try { String line;
FileReader in = new FileReader(f);  try {
buffer = new char [(int) f.length()]; BufferedReader in = new BufferedReader(new
in.read(buffer); InputStreamReader(System.in)); 
System.out.println(buffer); while ((line = in.readLine()) != null)
in.close(); System.out.println(line);
in.close();
} catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
}}} }
}
M. El Dick M. El Dick
}

BufferedReader vs Scanner BufferedReader vs Scanner


 Checking End of File/Stream (EOF)  Parsing primitive types
 BufferedReader  BufferedReader
 readLine() returns null  read(), readLine(), … none for parsing types
 read() returns -1  Needs StringTokenizer then wrapper class methods like
Integer.parseInt(token)
 Scanner
 nextLine() throws exception  Scanner
 Needs hasNextLine() to check first  nextInt(), nextFloat(), … for parsing types
 nextInt(), hasNextInt(), …
Class StringTokenizer Example
 BufferedReader methods  Display the words separated by any of the following
 Can read a line and a character, but not a single characters:
word  space, new line (\n), period (.) or comma (,)
String inputLine = in.readLine();
StringTokenizer wordFinder =
 StringTokenizer class new StringTokenizer(inputLine, " \n.,");
//the second argument is a string of the 4 delimiters
 Can parse a line into words while(wordFinder.hasMoreTokens())
{
 import java.util.* System.out.println(wordFinder.nextToken());
}

Text I/O vs. Binary I/O Binary I/O


31 32

 More efficient!
 No encoding or decoding required
 Portability

Java class files are binary files.


They can run on a JVM on any machine

M. El Dick M. El Dick
Binary I/O Classes The FileOutputStream Class
33 34

Methods write(int byte)


write(byte[] buffer)
flush()

Construction File f = new File(“temp.dat”);


FileOutputStream w = new FileOutputStream (f);

FileOutputStream w = new FileOutputStream


(“temp.dat”);

M. El Dick M. El Dick

The BufferedOutputStream Class The DataOutputStream Class


35 36

Methods flush() Methods writeBoolean(boolean b)


write(int byte) writeByte(int b)
write(byte[] buffer, int off, int len) writeChar(char c) writeUTF(String s)
writeInt(int i)

Construction …
Construction DataOutputStream d =
new DataOutputStream
(new FileOutputStream (“temp.dat”));

Converts primitive type values and strings into bytes and


outputs the bytes to the stream
M. El Dick M. El Dick
Example The FileInputStream Class
37 38

import java.io.*;
public class ByteFileOutput { Methods int read() (one byte)
public static void main (String args[]){ byte[] read(byte[] buffer)
int[] p  = { 1, 2, 3, 5, 7, 11, 19, 23}; long skip(long n)
try {
DataOutputStream s = new DataOutputStream(new
FileOutputStream ("primes.bin"));
Construction File f = new File(“temp.dat”);
for (int i = 0; i<p.length; i++)
FileInputStream w = new FileInputStream (f);
s.writeInt(p[i]);
s.close();
FileInputStream w = new FileInputStream
} catch (IOException e) {
(“temp.dat”);
e.printStackTrace();
}
}
M. El Dick M. El Dick
}

The BufferedInputStream Class The DataInputStream Class


39 40

Methods int read() (one byte) Methods boolean readBoolean()


byte[] read() byte readByte()
char readChar() String readUTF()
int readInt()

Construction …
Construction DataInputStream d =
new DataInputStream
(new FileInputStream (“temp.dat”));

Reads bytes from stream and converts them into primitive type
M. El Dick values or strings as M.
appropriate
El Dick
Example Example: Student grades
41 42

import java.io.*;
 Problem:
public class CharacterFileOutput {
public static void main (String args[]){  Write student names and grades to a binary file
try {  Read the data back from the file
File f = new File ("primes.bin");
DataInputStream s = new DataInputStream (new FileInputStream
(f));
int size = (int) f.length()/ 4; // 4 bytes per int
for (int i = 0; i<size; i++){
int p = s.readInt();
System.out.println(p);
}
s.close();
} catch (IOException e) {
e.printStackTrace();
M. El Dick M. El Dick
}}}

43 44

M. El Dick M. El Dick
Example: Copying Files
45 46

M. El Dick M. El Dick

Example: Detecting End of File


47 48

M. El Dick M. El Dick
Random-Access Files
49 50

 Two modes
 “r” read-only
 “rw” read and write

RandomAccessFile raf = new


RandomAccessFile("test.dat", "rw");

M. El Dick M. El Dick

File Pointer Example


51 52

 Initial position: file beginning

M. El Dick M. El Dick
Exercise 1: Converting text into UTF
53 54

 Write a program that reads lines of characters


from a text file and writes each line as a UTF-8
string into a binary file
 Display the sizes of the text file and the binary
file

M. El Dick M. El Dick

public static void main(String[] args) {

Exercise 2:
File textfile = new File ("f1.txt");
File binfile = new File ("f2.bin");
try{
55 BufferedReader br = new BufferedReader(new FileReader(textfile)); 56
DataOutputStream dos = new DataOutputStream (new
FileOutputStream(binfile));  Write a program that removes from a text file
String line;
int i=0; all the occurrences of a string that is given as a
while((line =br.readLine())!=null){
System.out.println(i+" "+line); parameter
dos.writeUTF(line);
i++;  Hint: Use the I/O classes that are character-
}
br.close();
oriented.
dos.close();
System.out.println("The text file size is "+textfile.length());
System.out.println("The binary file size is "+binfile.length());
}
catch(IOException e){
e.printStackTrace();
}
}

M. El Dick M. El Dick
Exercise 3: Exercise 4:
57 58

 Write a program that can:  Phone directory is stored in a binary file


 Take 3 parameters:  Phone entry (first name 10 chars max, last name 10
 Name of text file chars max, phone number 8 digits)
 2 strings s1and s2  Retrieve first/last/previous/next entry
 Replace inside file all occurrences of s1 by s2  Add new entry

M. El Dick M. El Dick

You might also like