You are on page 1of 66

Computing II

Tutorial 4

Prepared by: Ng Mee Mee


Key Concepts of Unit 3

 Manipulate files in Java


 Classify byte streams and character streams
 Explain Java exceptions and their handling
 Apply Java streams
 Manipulate the standard streams.
File Input/Output
 File: An area in secondary storage used to
hold information.

 You can write programs to read data from an


existing file for processing or write operation
results to a file for further processing.

 In order to perform File Input/Output


operations, you need to import the java.io
package.
The java.io.File
class java.io.File

+File(pathname: String) Creates a File object for the specified pathname. The pathname may be a
directory or a file.
+File(parent: String, child: String) Creates a File object for the child under the directory parent. child may be a
filename or a subdirectory.
+File(parent: File, child: String) Creates a File object for the child under the directory parent. parent is a File
object. In the preceding constructor, the parent is a string.
+exists(): boolean Returns true if the file or the directory represented by the File object exists.
+canRead(): boolean Returns true if the file represented by the File object exists and can be read.
+canWrite(): boolean Returns true if the file represented by the File object exists and can be written.
+isDirectory(): boolean Returns true if the File object represents a directory.
+isFile(): boolean Returns true if the File object represents a file.
+isAbsolute(): boolean Returns true if the File object is created using an absolute path name.
+isHidden(): boolean Returns true if the file represented in the File object is hidden. The exact
definition of hidden is system-dependent. On Windows, you can mark a file
hidden in the File Properties dialog box. On Unix systems, a file is hidden if
its name begins with a period character '.'.
+getAbsolutePath(): String Returns the complete absolute file or directory name represented by the File
object.
+getCanonicalPath(): String Returns the same as getAbsolutePath() except that it removes redundant
names, such as "." and "..", from the pathname, resolves symbolic links (on
Unix platforms), and converts drive letters to standard uppercase (on Win32
platforms).
+getName(): String Returns the last name of the complete directory and file name represented by
the File object. For example, new File("c:\\book\\test.dat").getName() returns
test.dat.
+getPath(): String Returns the complete directory and file name represented by the File object.
For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.dat.
+getParent(): String Returns the complete parent directory of the current directory or the file
represented by the File object. For example, new
File("c:\\book\\test.dat").getParent() returns c:\book.
+lastModified(): long Returns the time that the file was last modified.
+delete(): boolean Deletes this file. The method returns true if the deletion succeeds.
+renameTo(dest: File): boolean Renames this file. The method returns true if the operation succeeds.
Manipulating a file by showing
file information
 Please refer course material Unit 3.1,on page
7 – Figure 3.1 FileExpert.java & Figure 3.2
TestFile.java
 The program will demonstrate the use of the
methods in the File class to obtain their
properties.
Understanding of Input/Output
stream
FileReader input = new FileReader("temp.txt");
int code = input.read();
System.out.println((char)code);

FileWriter output = new FileWriter("temp.txt");


output.write("Java 101");
output.close();
File Input/Output
Java file I/O process:
1. Import necessary classes from the packages
java.util and java.io into the program.
2. Create and associate appropriate objects
with the input/output sources.
3. Use the appropriate methods associated
with the variables created in Step 2 to
input/output data.
4. Close the files.
Binary File vs. Textual File
 Data stored in a text file are represented in human-readable
form. Data stored in a binary file are represented in binary
form. You cannot read binary files. Binary files are designed
to be read by programs. For example, the Java source
programs are stored in text files and can be read by a text
editor, but the Java classes are stored in binary files and are
read by the JVM. The advantage of binary files is that they are
more efficient to process than text files.

 A text file consists of a sequence of characters and a binary


file consists of a sequence of bits. For example, the decimal
integer 199 is stored as the sequence of three characters: '1',
'9', '9' in a text file and the same integer is stored as a byte-
type value C7 in a binary file, because decimal 199 equals to
hex C7.
The hierarchy of the data units
corresponding to their
input/output stream
 Please refer course material Unit3 on page12
– Figure3.3
Text I/O Classes

InputStreamReader FileReader
Reader
BufferedReader

Object BufferedWriter

Writer OutputStreamWriter FileWriter

PrintWriter
FileReader
To construct a FileReader, use the following
constructors:
public FileReader(String filename)

public FileReader(File file)

A java.io.FileNotFoundException would

occur if you attempt to create a FileReader


with a nonexistent file.
Sample TestFileReader.jav
Code
a
import java.io.*;
public class TestFileReader {
public static void main(String[] args)throws IOException {
// Create an input stream
FileReader input =new FileReader("temp.txt");
int code;
// Repeatedly read a character and display it on the console
while ((code = input.read()) != -1)
System.out.print((char)code);
input.close(); // Close the stream
}

}
FileWriter
To construct a FileWriter, use the following constructors:

 public FileWriter(String filename)


 public FileWriter(File file)

 public FileWriter(String filename, boolean append)

 public FileWriter(File file, boolean append)

If the file does not exist, a new file would be created. If the file
already exists, the first two constructors would delete the
current contents in the file.
To retain the current content and append new data into the file,
use the last two constructors by passing true to the append
parameter.
Sample
Code TestFileWriter.java
import java.io.*;
public class TestFileWriter {
public static void main(String[] args) throws IOException {
// Create an output stream to the file
FileWriter output = new FileWriter("temp.txt", true);

// Output a string to the file


output.write("Introduction to Java");

// Close the stream


output.close();
}

}
Binary I/O Classes
FileInputStream
DataInputStream
InputStream FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream BufferedOutputStream

OutputStream FilterOutputStream DataOutputStream

ObjectOutputStream PrintStream
FileInputStream
To construct a FileInputStream, use the following
constructors:
public FileInputStream(String filename)

public FileInputStream(File file)

A java.io.FileNotFoundException would occur if you

attempt to create a FileInputStream with a


nonexistent file.
FileOutputStream
To construct a FileOutputStream, use the following
constructors:
 public FileOutputStream(String filename)

 public FileOutputStream(File file)

 public FileOutputStream(String filename, boolean append)

 public FileOutputStream(File file, boolean append)

If the file does not exist, a new file would be created. If the file
already exists, the first two constructors would delete the
current contents in the file. To retain the current content and
append new data into the file, use the last two constructors by
passing true to the append parameter.
Key Concepts of Unit 5

 Describe the usage of data structure


 Apply java collection
 Develop simple data structures: Queue
 Apply wrapper classes
 Apply string manipulation with String classes
Data Structures
 Data structures is a collection of data that can
handled or processed under a single name
 For example:
 A a time object encapsulates the data items for hour,
minute and second
 An array that used to store a group of data items of the
same type.
 List, Map and Set are three data structures provided
by the Java standard software library with the
subclasses of Java interface Collection
Stack
 Stack is a data structure that maintains a collection
of data items.
 It also called a Last-In-First-Out (LIFO) structure.
 What we do with a Stack:
 Push: add a new value.
 Pop: Remove a value.
 The last item added is the first removed.
 Think of a stack of plates.
Conceptually, a Stack carries out the idea of top-
down design.
Review: Stacks — What a Stack Is
1. Start: 1. Pop. 5
an empty Stack. 2

Push 2. 3. Pop.
3.
2 2

5. Push 7. 7
5. Pop. Stack is empty again.
2

8. Pop. 7. Push 7.
2 7

9. Etc. …
11. Push 5. 5
2

14. Push 5. 5
5
2
Activity 5.2

 What are the two operations of a stack?


Vector

 Vector is a data structure( a way of storing


data in memory) similar to an array.
 A vector can grow at run time but an array
has got a fixed size.
 A vector include only objects (i.e., instances
of classes) and not support elements of
primitive types (i.e., int, float etc).
 A wrapper class(i.e., Integer, Float) is needed
to store an item of primitive types.
Members of the class Vector
Members of the class Vector
Vectors
 Every element of a Vector object is a
reference variable of the type Object.
 To add an element into a Vector object:
 Create appropriate object.
 Store data into object.
 Store address of object holding data into Vector
object element.
Sample Code: FindVector.java

 Pls refer course material, Unit 5 on page 13


for FindVector.java
Self-Test 5.1

 Differentiate array with vector in Java.


Collections

 Collection represents a group of objects,


known as its elements.
 A common data structures such as List, Set
and Map are the subclasses of the Java
interface Collection in java.util package.
 Pls refer course unit 5-2 on page 18 for the
methods of a Collection object.
List
 List interface maintains data items with a predefined
order among them.
 For example,
 A shopping list
 A student names list
 List is a specific type of Collection object.
 Example of List data structure is ArrayList,
LinkedList and Vector.
 Pls refer course material Unit 5.2 on page 20 for the
methods of a List object
Set

 A Set is a collection of unique elements or


items, which no elements or items are
duplicated in a set.
 HashSet class is an example of set data
structure.
 A Set object is a specific type of Collection
object.
 Pls refer course material Unit 5.2 on page 26
for the program TestHashSet1 class.
Maps

 The Map interface maps keys to the


elements. The keys are like indexes.
 In List, the indexes are integer. In Map, the
keys can be any objects.
 HashMap class is an example of Map data
structure.
Choosing suitable collection
types and implementation
 Pls refer course material Unit 5.2 on page 30,
Figure 5.20 A flowchart for choosing a
suitable data structure.
Iterators

 Iterator is a Java interface defined in java.util


package.
 It defined three methods:
 Public boolean hasNext()
 Public Object Next()
 These methods is used for iterating the
objects maintained by a Collection object.
Queue
 A queue is a storage or data structure that maintains a collection
of data or objects to be processed.
 A Queue is a First-In-First-Out (FIFO) structure.
 What we do with a Queue:

 Enqueue: add a new value at the back.

 Say “N Q”.
 Dequeue: Remove a value at the front.

 Say “D Q”.
 The first item added is the first removed.

 Think of people standing in line. (This is also a good way to


remember which end is “front” and which is “back”.)
 Some people use other words for “enqueue” & “dequeue”.

 “Push” and “pop”, for example.

 So a Queue is another restricted version of a Sequence.


 We can only insert at one end and remove at the other.

 We (usually) cannot iterate through the contents.


Queues: What a Queue Is — Illustration
1. Start: 1. Dequeue. 5 5
F B
F B
an empty Queue.
3. Dequeue. 5
F B
3. Enqueue 2. 2
F B
5. Dequeue.
F B
5. Enqueue 7. 2 7
F B Queue is empty again.
7. Dequeue.
7 7
F B 7. Enqueue 7. F B

9. Enqueue 5. 7 5
F B 9. Etc. …
11. Enqueue 5.
7 5 5
F B

Compare this with Stack!


Queues
What a Queue Is — Waiting
Conceptually, a Queue carries out the idea of waiting
in line.
 Items that need to be processed are enqueued.
 When we are able to process an item, we dequeue it and
process it.
 As long as the processor keeps going, no item languishes
forever. They are all processed eventually.
In practice, nearly every use of a Queue has this idea
behind it.
Activity 5.5

 Differentiate a Stack with a Queue.


Wrapper Class

 A wrapper class is used to encapsulate


primitive values so that these values can be
maintained by a reference variable.
 There are eight wrapper classes for eight
primitive types. See Unit 5.4, on page 47
String

 Used to manipulate strings.


 String:
 Sequence of zero or more characters.
 Enclosed in double quotation marks.
 Null or empty strings have no characters.
 Numeric strings consist of integers or decimal
numbers.
 Length is the number of characters in a string.
The class String

 String variables are reference variables.


 Given:
String name;

 Equivalent statements:
name = new String("Lisa Johnson");
name = "Lisa Johnson";
The class String
 A String object is an instance of class String.

 A String object with the value "Lisa Johnson"


is instantiated.

 The address of the object is stored in name.

 The new operator is unnecessary when


instantiating Java strings.

 String methods are called using the dot


operator.
Some Commonly Used String
Methods
Some Commonly Used String
Methods
Some Commonly Used String
Methods
Some Commonly Used String
Methods
Additional String Methods
Additional String Methods
Additional String Methods
Additional String Methods
Effects of Some String
Methods
Example: create String
object
public class StringDemo {

public static void main(String[] args) {


String message = new String("Welcome to Java!");
String myname ="Wendy Ho";
String college = new String();
college ="Southern";

System.out.println(message);
System.out.println(myname);
System.out.println(college);
}
}
Example: the length()
method
public class LengthDemo {

public static void main(String[] args) {


String message ="welcome";
System.out.println(message.length());
}
}
Example: the charAt()
method
public class CharAtDemo {

public static void main(String[] args) {


String message = new String("Welcome to
Java!");

System.out.println(message.charAt(0));

}
}
Example: String
Concatenation
public class ConcatDemo {

public static void main(String[] args) {


String s1 = new String("Welcome");
String s2 = "to Java!";
String s3=s1 + s2;

System.out.println(s3);
System.out.println(s1.concat(s2));

}
}
Example: the substring()
method
public class SubstringDemo {

public static void main(String[] args) {


String s1 = "Welcome to Java";
String s2 = s1.substring(0,11) + "HTML";
System.out.println(s1);
System.out.println(s2);

}
}
Example: equals() and ==
operator
public class EqualsDemo {

public static void main(String[] args) {


String s1 = new String("Welcome");
String s2 = "welcome";

if(s1.equals(s2)){
System.out.println("s1 and s2 have the same content");
}
else{
System.out.println("s1 and s2 do not have the same content");
}
if(s1 == s2){
System.out.println("s1 and s2 have the same reference");
}
else{
System.out.println("s1 and s2 do not have the same reference");
}

}
}
Example: compareTo()
method
public class CompareToDemo {

public static void main(String[] args) {


String s1 = new String("Welcome");
String s2 = "Welcome";

if(s1.compareTo(s2)> 0){
System.out.println("s1 is greater than s2");
}else if(s1.compareTo(s2) == 0){
System.out.println("s1 and s2 have the
same contents");
}else{
System.out.println("s1 is less than s2");
}
}
}
Example: String
Conversions
public class ConversionsDemo {
public static void main(String[] args) {
String s1 = new String("Welcome");
String s2 = " to ";
String s3 = " Java ";

System.out.println(s1.toUpperCase());
System.out.println(s1.toLowerCase());
System.out.println(s2);
System.out.println(s3.trim());
System.out.println(s3.replace("a","o"));

}
}
Example: the indexOf()
method
public class indexOfDemo {
public static void main(String[] args) {
String s1 = new String("Welcome to Java");

System.out.println(s1.indexOf('W'));
System.out.println(s1.indexOf('x'));
System.out.println(s1.indexOf('o',5));
System.out.println(s1.indexOf("come"));
System.out.println(s1.indexOf("Java",5));
System.out.println(s1.lastIndexOf('a'));

}
}
Self-test 5.5

 Q1,Q2
Question 1

 Assume that the str1 variable contains the


string “Today is Wednesday.” What will the
following function return?
a) str1.length( )
b) str1.substring(9,18)
c) str1.replace(‘d’, ‘*’)
d) str1.indexOf(“is”,6)
Question 2
 Suppose s is a string with the value "java".
What will be assigned to x if you
execute the following code?
char x = s.charAt(4);
a. 'a'
b. 'v'
c. Nothing will be assigned to x, because the
execution causes the runtime error
StringIndexOutofBoundsException.
d. None of the above.
Question 3

 How can you initialize a string with "123"?


a. String[] string = {'1', '2', '3'};
b. String string = {'1', '2', '3'};
c. String s = "123";
d. String s = new String("123");
e. c and d are both fine, but c is better.
Summary
 Collection contain references to objects that are all
of the same type.
 A List object maintains the order among the objects
so that each object can be accessed by specifying
index.
 A Set object can be used to maintain a collection of
objects with no duplications.
 A Map object can be used if it is necessary to
maintain the key-value object pairs.
 Vector is a data structure which is similar to an array
but it can grow at run time, as long as there is
enough computer memory available.
Summary
 Queue, a data structure where elements are
removed in the same order they were entered (First
In, First Out).
 Stack, a data structure where you can only access
the item at the top (Last In, First Out)
 Iterator is an interface which is used to trace the
elements of a Collection step by step.
 The String class represents character strings.
 String are constant or immutable; their values
cannot be changed after they are created.

You might also like