Download SCJP_Chapter6_String,IO&Exception

Document related concepts
no text concepts found
Transcript
Strings, I/O,
Formatting,
and Parsing
String, StringBuilder, and
StringBuffer
The String Class
• String are immutable objects
• Create an instance of String with the
keyword "new“
• Example:
– String s = new String();
– String s = new String("abcdef");
– String s = "abcdef";
The String Class
The String Class
The String Class
The String Class
• Another example:
The String Class
• Output:
The String Class
• And now?
The String Class
• Example:
The String Class
• Que imprime?:
The String Class
• Imprime "spring winter spring summer".
Important facts about String and
memory
• JVM reserve a special area called "Sreing constant
pool”
• When the compiler encounters a string literal, it
checks the pool to see if it exists. If found, the
literal reference to the new addresses the existing
chain (the existing chain has an additional
reference.) [Immutable]
new String
String Class Methods
String Methods
• public char charAt(int index)
String x = "airplane";
System.out.println( x.charAt(2) );
// output ‘r’
String Methods
• public String concat(String s)
String x = "taxi";
System.out.println( x.concat(" cab") );
// output is "taxi cab"
String Methods
• public boolean equalsIgnoreCase(String s)
String x = "Exit";
System.out.println(x.equalsIgnoreCase("EXIT");
// is "true“
System.out.println(x.equalsIgnoreCase("tixe"));
// is "false"
String Methods
• public int length()
String x = "01234567";
System.out.println( x.length() );
// returns "8"
String Methods
• public String replace(char old, char
new)
String x = "oxoxoxox";
System.out.println( x.replace('x', 'X') );
// output is "oXoXoXoX"
String Methods
• public String substring(int begin)
• public String substring(int begin, int end)
String x = "0123456789";
System.out.println( x.substring(5) );
// output is "56789"
System.out.println( x.substring(5, 8));
// output is "567"
String Methods
• public String toLowerCase()
String x = "A New Moon";
System.out.println( x.toLowerCase() );
// output is "a new moon"
String Methods
• public String toUpperCase()
String x = "A New Moon";
System.out.println( x. toUpperCase() );
// output is “A NEW MOON"
String Methods
• public String trim()
String x = " hi ";
System.out.println( x + "x" );
// result is " hi x"
System.out.println( x.trim() + "x");
// result is "hix"
The StringBuffer and
StringBuilder Classes
• Java.lang.StringBuilder and
java.lang.StringBuffer classes should be used
when making several modifications to the
strings.
• Unlike String, objects of type StringBuffer
and StringBuilder can be modified again and
again without leaving behind discarded
objects
• A common use of StringBuffer and
StringBuilder is on file I / S
StringBuffer vs. StringBuilder
• The StringBuilder class was added in Java 5.
• StringBuilder is Not thread safe. In other
words, their methods are not synchronized
(Chapter 9)
• Sun recommends that StringBuilder instead
of StringBuffer whenever possible because
StringBuilder will run faster.
Using StringBuffer and
StringBuilder
• StringBuffer
• StringBuilder
Key methods of StringBuffer
and StringBuilder
• public synchronized StringBuffer append(String s)
StringBuffer sb = new StringBuffer("set ");
sb.append("point");
System.out.println(sb);
// output is "set point“
StringBuffer sb2 = new StringBuffer("pi = ");
sb2.append(3.14159f);
System.out.println(sb2);
// output is "pi = 3.14159"
Key methods of StringBuffer
and StringBuilder
• public StringBuilder delete(int start, int
end)
StringBuilder sb =
new StringBuilder("0123456789");
System.out.println(sb.delete(4,6));
// output is "01236789"
Key methods of StringBuffer
and StringBuilder
• public StringBuilder insert(int offset, String
s)
StringBuilder sb =
new StringBuilder("01234567");
sb.insert(4, "---");
System.out.println( sb );
// output is "0123---4567"
Key methods of StringBuffer
and StringBuilder
• public synchronized StringBuffer reverse()
StringBuffer s =
new StringBuffer("A man a plan a canal
Panama");
sb.reverse();
System.out.println(sb);
// output: "amanaP lanac a nalp a nam A"
Key methods of StringBuffer
and StringBuilder
• public String toString()
StringBuffer sb =
new StringBuffer("test string");
System.out.println( sb.toString() );
// output is "test string"
File Navigation and I/O
• File .- The API says that the kind of file is
"an abstract representation n of a file and
directory path. " The File class is not used
for reading or writing data, is used to work
at high level, creating new files, search
files, delete files, create directories, and
working with paths (path).
File Navigation and I/O
• FileReader .- This class is used to read
character files. The method read() is very
low, allowing you to read the entire flow
(stream) character. FileReaders often
surrounded by objects of more s high level,
BufferedReaders, which improves
performance and provides the means most
convenient to work s with the data.
File Navigation and I/O
• BufferedReader.- In comparison with
FileReaders n, BufferedReaders read into
relatively large data file at a time, and
maintains these data in a buffer. When
prompted for the next character or line of
data is retrieved from memory (minimizes the
time) and then perform read operations. In
addition s, BufferedReader provides methods
more suitable as readLine(), giving the next
line of arhiva
File Navigation and I/O
• FileWriter.- This class is used for writing
character files. His method write() to write
character (s) of strings or a file. FileWriter
are usually surrounded by writers such as
high-level objects or PrintWriters
BufferedWriters, which provide better
performance and higher, with more method
flexible to write the data.
File Navigation and I/O
• BufferedWriter.- Compared with FileWriters,
writes BufferedWriters relatively large pieces
of data from one file at a time, minimizes the
number of times of write operations to a file.
In addition, the BufferedWriter class provides
the method NewLine () that facilitates the
creation of line separators automatically.
File Navigation and I/O
• PrintWriter.- This class has been
improved significantly in Java 5.
Because it has new methods and
constructors (you can build a
PrintWriter from a File or String). New
methods like format (), printf () and
append () PrintWriter make it very
flexible and powerful.
Creating files using the File class
• File type objects are used to represent
the current files (but not data files) or
directories that exist on a physical
computer disk.
Creating files using the File
class File
• Solo se a creado el objeto File, no el
archivo físico.
Creating files using the File
class File
• The above code prints false, true, true
• If you run a second time, print: true, false,
true
• boolean exists() .- This method returns true
if it finds the specified file.
• boolean createNewFile() .- This method
creates a file if it is not exists.
• boolean isDirectory() .- This method returns
true if it finds the specified directory
Using FileWriter & FileReader
Using FileWriter & FileReader
• Output:
12 howdy
folks
Writer & Reader Hierarchy
Combining I/O
• Example 1 :
Combining I/O
• Example 2 :
Combining I/O
• Example 3 :
Combining I/O
• Example 4:
Combining I/O
• Example 4:
Combining I/O
• Example 5:
Combining I/O
• Example 6:
Serialization
• “Save this object and all its instance
variables"
Working with
ObjectOutputStream &
ObjectInputStream
•
•
•
•
ObjectOutputStream.writeObject()
// serialize and write
ObjectInputStream.readObject()
// read and deserialize
Working with
ObjectOutputStream &
ObjectInputStream
• Java.io.ObjectOutputStream and
java.io.ObjectInputStream classes are high
level in the java.io package, and as we
learned earlier, that means surrounding the
lower classes and java.io.FileInputStream
java.io.FileOutputStream
• Example 1:
• Example 2:
Dates, Numbers, and
Currency
Working with Dates,
Numbers, and Currencies
• java.util.Date The majority of the method
of this kind are obsolete, but can be used as
a bridge between the Calendar and
DateFormat class. A Date instance can
convert the date and time, to milliseconds.
• java.util.Calendar This class provides a
variety of methods who help make and
manipulate dates and times
Working with Dates,
Numbers, and Currencies
• java.text.DateFormat This class is
used to format dates. "01/01/70" ->
"January 1 1970”
• java.text.NumberFormat This class is
used to format numbers and local
currencies (Currencies) for everyone.
The Date Class
• Example 1
The Date Class
• Example 2
The Calendar Class
The DateFormat Class
The Locale Class
The Locale Class
The Locale Class
The NumberFormat Class
Summary
Parsing, Tokenizing and
Formatting
• Simple search:
Parsing, Tokenizing and
Formatting
• Searches using Metacharacters:
• source: a12c3e456f
• index: 0123456789
• pattern: \d
-> regex will tell us that it found digits at positions 1, 2, 4, 6, 7, and 8.
• In case of:
• source: “a 1 56 _Z”
• index: 0123456789
• pattern: \w
-> regex will tell us that it found digits at positions 0, 2, 4, 5, 7, and 8.
Parsing, Tokenizing and
Formatting
• In case of:
– source: "cafeBABE"
– index: 01234567
– pattern: [a-cA-C]
-> returns positions 0, 1, 4, 5, 6.
Parsing, Tokenizing and
Formatting
• Searches using Quantifiers:
• + : One or more occurrences
• * : Zero or more occurrences
• ? : Zero or one occurrences
• ^ : For example, with pattern: “proj1([^,])*”
=> Give me zero or more characters that
aren't a comma
Parsing, Tokenizing and
Formatting
• The Predefined Dot: "any character can
serve here."
– source: "ac abc a c"
– pattern: a.c
=> will produce the output
• 3 abc
•7ac
Parsing, Tokenizing and
Formatting
• Searching Using the Scanner Class:
import java.util.*;
class ScanIn {
public static void main(String[] args) {
System.out.print("input: ");
System.out.flush();
try {
Scanner s = new Scanner(System.in);
String token;
do {
token = s.findInLine(args[0]);
System.out.println("found " + token);
} while (token != null);
} catch (Exception e) { System.out.println("scan exc"); }
}
}
•
The invocation and input
java ScanIn "\d\d"
input: 1b2c335f456
•
produce the following:
found 33
found 45
found null
Parsing, Tokenizing and
Formatting
• Tokenizing with String.split()
import java.util.*;
class SplitTest {
public static void main(String[] args) {
String[] tokens = args[0].split(args[1]);
System.out.println("count " + tokens.length);
for(String s : tokens)
System.out.println(">" + s + "<");
}
}
* java SplitTest "ab5 ccc 45 @" "\d"
Output: count 4 >ab<
> ccc <
><
> @<
Parsing, Tokenizing and
Formatting
• Tokenizing with Scanner
FIN