1. Strings
Liang covers this work inReading: Liang Sect 14.11
and you should read through this very carefully.
1.1 Java Strings
Java provides a powerful String class. Conceptually, Java strings are sequences of Unicode characters. To use it you need to import java.lang.String.The class offers several constructors for creating a string object. The following demonstrates several examples
String myStr1 = new String(“This is the first example”);
String myStr2 = “The second example”;
char[] charArray = {‘T’,’h’,’e’,’ ’,’t’,’h’,’i’,’r’,’d’,
’ ’,’o’,’n’,’e’};
String myStr3 = new String(charArray); //from char array
String variables are the references to String objects.
A String object is immutable; its contents cannot be changed. Check the example on page 336 (p.326 8E).
1.2 Substrings and concatenation
The String class provides many useful methods. For example, you can extract part of a larger string with the substring method. Here is an example:
String mySubject = “ITC521 Java 2”;
String s = mySubject.substring(0, 6);
which creates a string consisting of the first 6 characters in the string mySubject.
You can use the + sign to join (concatenate) two strings:
String code = “ITC521”;
String name=”Java 2”;
String subject = code + name;
Now the string subject is “ITC521Java 2”. Please note there is no space between ITC521 and Java.
1.3 String comparisons
You cannot use the comparison operators like <, <=, >=, > etc to compare two string objects. You must use the class method compareTo.
To check if the contents of two string variables are equal, please use the equalsmethod. A common mistake is to use like string1==string2 which compares the reference rather than the contents of string1 and string2. Please consult to the explanation on pages 337-338 (p.327-328 8E).
You cannot use the comparison operators like <, <=, >=, > etc to compare two string objects. You must use the class method compareTo.
To check if the contents of two string variables are equal, please use the equalsmethod. A common mistake is to use like string1==string2 which compares the reference rather than the contents of string1 and string2. Please consult to the explanation on pages 337-338 (p.327-328 8E).
1.4 More other methods
I suggest you should have a quick look at the tables on pages 337-344 (p.327-334 8E) which list most of the String methods.
I suggest you should have a quick look at the tables on pages 337-344 (p.327-334 8E) which list most of the String methods.
2. Text File I/O
This section introduces how to read/write strings and numeric values from/to a text file using the Scanner and PrintWriter classes.
This section introduces how to read/write strings and numeric values from/to a text file using the Scanner and PrintWriter classes.
2.1 Write data to a file
If you are going to write data to a text file, please follow the following template to write your program.
// File: WriteData.java
/* A program which write some data onto a text file
*/
import java.io.*;
public class WriteData
{
public static void main( String[] argv )
{
PrintWriter output;
try
{
output = new PrintWriter( "temperature.txt" );
}
catch( IOException e ) //Failure in creating the file
{
System.err.println( "Error - cant create the file." );
return;
}
try
{
output.print( “Today’s minimal temperature: ” );
output.println( 21.3 + “ degree.” );
output.print( “Yesterday’s maximal temperature: ”);
output.println( 35.0 + “ degree.” );
//Or write anything you want.
output.close(); // You need to close the file
}
catch( IOException e )
{
System.err.println ( "Error - cant write a character, an IOException occurred" );
return;
}
}// end main
}// end class
If you are going to write data to a text file, please follow the following template to write your program.
// File: WriteData.java
/* A program which write some data onto a text file
*/
import java.io.*;
public class WriteData
{
public static void main( String[] argv )
{
PrintWriter output;
try
{
output = new PrintWriter( "temperature.txt" );
}
catch( IOException e ) //Failure in creating the file
{
System.err.println( "Error - cant create the file." );
return;
}
try
{
output.print( “Today’s minimal temperature: ” );
output.println( 21.3 + “ degree.” );
output.print( “Yesterday’s maximal temperature: ”);
output.println( 35.0 + “ degree.” );
//Or write anything you want.
output.close(); // You need to close the file
}
catch( IOException e )
{
System.err.println ( "Error - cant write a character, an IOException occurred" );
return;
}
}// end main
}// end class
2.2 Read data from a text file
Java provides the class java.util.Scanner for parsing primitive types and strings from the console or a text file. It usually breaks its input into tokens delimited by whitespaces characters.
import java.io.*;
import java.util.Scanner;
public class TextScanner {
public static void main(String[] args) {
Scanner input;
try
{
input = new Scanner( new FileReader("temperature.txt") );
}
catch( IOException e ) //Fail to open the file
{
System.err.println( "Error - cant create the file." );
return;
}
try{
while (input.hasNext()) {
System.out.println(input.next());
}
input.close();
}
catch (IOException e)
{
System.err.println ( "Error - cant read data, an
IOException occurred" );
return;
}
}// Main
} // Class
You can change the default delimeter (whitespace) that is used to tokenize the input, through the useDelimiter method of Scanner.
Java provides the class java.util.Scanner for parsing primitive types and strings from the console or a text file. It usually breaks its input into tokens delimited by whitespaces characters.
import java.io.*; import java.util.Scanner; public class TextScanner { public static void main(String[] args) { Scanner input;try
{
input = new Scanner( new FileReader("temperature.txt") );
}
catch( IOException e ) //Fail to open the file
{
System.err.println( "Error - cant create the file." );
return;
}
try{
while (input.hasNext()) { System.out.println(input.next()); } input.close();}
catch (IOException e)
{
System.err.println ( "Error - cant read data, an
IOException occurred" );
return;
}
}// Main
} // Class
You can change the default delimeter (whitespace) that is used to tokenize the input, through the useDelimiter method of Scanner.
3. Binary File I/O
The base binary I/O classes are InputStream/OutputStream. Please have a close look at Figure 19.3 on page 712 (p.676 8E).
The base binary I/O classes are InputStream/OutputStream. Please have a close look at Figure 19.3 on page 712 (p.676 8E).
3.1 Input/Output in terms of bytes
If you want to input/output data from/to binary files, the simplest classes areFileInputStream/FileOutputStream. First, create an object ofFileInputStream/FileOutputStream, then use read/write function to input/output data in terms of bytes.
Read the following program and test it
import java.io.*;
public class TestFileStream {
public static void main(String[] args) {
try{
FileOutputStream output = new
FileOutputStream("temp1.dat");
for (int i=0; i<=10; i++)
output.write(i);
output.close();
}
catch (IOException e) {
System.out.println("Error!");
return;
}
try{
FileInputStream input = new
FileInputStream("temp1.dat");
int value;
while ((value=input.read()) != -1)
System.out.print(value+" ");
input.close();
}
catch (IOException e) {
System.out.println("Error!");
return;
}
}
}
The integer was written into the file as a single byte. To see this, changeoutput.write(i) to output.write(i*125) and run the program again.
If you want to input/output data from/to binary files, the simplest classes areFileInputStream/FileOutputStream. First, create an object ofFileInputStream/FileOutputStream, then use read/write function to input/output data in terms of bytes.
Read the following program and test it
import java.io.*;
public class TestFileStream {
public static void main(String[] args) {
try{
FileOutputStream output = new
FileOutputStream("temp1.dat");
for (int i=0; i<=10; i++)
output.write(i);
output.close();
}
catch (IOException e) {
System.out.println("Error!");
return;
}
try{
FileInputStream input = new
FileInputStream("temp1.dat");
int value;
while ((value=input.read()) != -1)
System.out.print(value+" ");
input.close();
}
catch (IOException e) {
System.out.println("Error!");
return;
}
}
}
The integer was written into the file as a single byte. To see this, changeoutput.write(i) to output.write(i*125) and run the program again.
3.2 Data Input/Output as bytes
The read/write method provided in FileInputStream/FileOutputStreamonly offer the capacity of reading/writing bytes. To read/write meaningful values and strings in the format of bytes, you should use theDataInputStream/DataOutputStream classes. Both classes define a lot of read/write methods for primitive values and strings, for example, readInt for reading an integer.
It is easy for you to convert TestFileStream.java to a new program usingDataInputStream/DataOutputStream . You can use the available() method to test if it is at the end of the stream. Please try it.
The read/write method provided in FileInputStream/FileOutputStreamonly offer the capacity of reading/writing bytes. To read/write meaningful values and strings in the format of bytes, you should use theDataInputStream/DataOutputStream classes. Both classes define a lot of read/write methods for primitive values and strings, for example, readInt for reading an integer.
It is easy for you to convert TestFileStream.java to a new program usingDataInputStream/DataOutputStream . You can use the available() method to test if it is at the end of the stream. Please try it.
4. Serialization and Object I/O
These are dealt with in
Reading: Liang 19.6
which you should read carefully.
These are dealt with in
Reading: Liang 19.6
which you should read carefully.
4.1 Object Streams
Sometimes we want to store object information created in a program. For example, we may have a collection of Employee objects and want to save it in a file.ObjectInputStream/ObjectOutputStream helps us to perform I/O for objects in addition to primitive type values and strings. Have a close look at Figures 19.15 and 19.16.
Sometimes we want to store object information created in a program. For example, we may have a collection of Employee objects and want to save it in a file.ObjectInputStream/ObjectOutputStream helps us to perform I/O for objects in addition to primitive type values and strings. Have a close look at Figures 19.15 and 19.16.
4.2 Storing Objects to a file
The basic steps are
- Open an ObjectOutputStream object by
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream(“statistic.dat”));
- To save an object, use the writeObject method
out.writeObject(new Date());
- To save an string, use the writeUTF method to write a string
out.writeUTF(“John”);
The basic steps are
- Open an ObjectOutputStream object by
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream(“statistic.dat”));
- To save an object, use the writeObject method
out.writeObject(new Date());
- To save an string, use the writeUTF method to write a string
out.writeUTF(“John”);
4.3 Reading Objects from a file
Reading objects from a file is a bit more complicated than storing objects to a file. When reading, we must read the object type, create a blank object of that type, and fill it with the data that we stored in the file. However most of this job will be automatically done for you.
An ObjectInputStream object should be created and linked with a file by
ObjectInputStream input = new ObjectInputStream(new
FileInputStream(“statistic.dat”));
Then you can read objects with the readObject method. Also Java’s safe casting should be used to get the desired type. For example,
Date newdate = (Date)(input.readObject());
For primitive type values, you use methods such as readInt, readDouble, andreadUTF etc. You must make sure that the objects or primitive values are read back from the corresponding order as they were written.
Be careful: the readObject method may throw ClassNotFoundException, so you should have catch clause for this in your code.
Reading objects from a file is a bit more complicated than storing objects to a file. When reading, we must read the object type, create a blank object of that type, and fill it with the data that we stored in the file. However most of this job will be automatically done for you.
An ObjectInputStream object should be created and linked with a file by
ObjectInputStream input = new ObjectInputStream(new
FileInputStream(“statistic.dat”));
Then you can read objects with the readObject method. Also Java’s safe casting should be used to get the desired type. For example,
Date newdate = (Date)(input.readObject());
For primitive type values, you use methods such as readInt, readDouble, andreadUTF etc. You must make sure that the objects or primitive values are read back from the corresponding order as they were written.
Be careful: the readObject method may throw ClassNotFoundException, so you should have catch clause for this in your code.
4.4 Serializable
Not every object can be written to an output stream. If you want to save and restore objects from your own class in an object stream, you must implement theSerializable interface like
class myClass implements Serializable { . . . }
Generally speaking you don’t need to change your class in any way because theSerializable interface has no methods.
Not every object can be written to an output stream. If you want to save and restore objects from your own class in an object stream, you must implement theSerializable interface like
class myClass implements Serializable { . . . }
Generally speaking you don’t need to change your class in any way because theSerializable interface has no methods.
No comments:
Post a Comment