Java examples explain the regular expression
Create a regular expression
You can start with something relatively simple learning the regular expression. To fully grasp how to construct the regular expression can look at the documents java.util.regex JDK the Pattern category of documents.
Character character B B \ 0 xhh xhh16 hexadecimal values expressed by the characters \ 0 xhhhh uhhhh16 hexadecimal values expressed by the Unicode characters \ tTab \ n newline \ r Enter at \ f-page website \ eEscape
Regular expressions are a powerful embodied in the character set definition of it (character class). Below are some of the most common character set and the definition of ways, in addition to some pre-defined character sets:
Character Set. Said arbitrary character [abc] that characters a, b, c of an arbitrary (a | b | c same) [^ abc] In addition to a, b, c of the arbitrary character of a (negative) a-zA-Z] from a to z or A to Z of the arbitrary character (range) [abc [hij] a, b, c, h, i, j in an arbitrary character (a | b | c | h | i | j same) (and sets) [az & [hij] h, i, j in a (common) \ s space characters (spaces button, tab, and for trip-page Enter ) \ S non-whitespace characters ([^ \ s]) \ d a figure, which is [0-9] \ D, a non-digital characters, that is, [^ 0-9] \ w characters of a word (word character ), that is, [a-zA-Z_0-9] \ W of the characters in a non-word, [^ \ w]
If you used other languages is the regular expression, you can see a unique backslashed. In other languages, "\ \" means "I just want to in the regular expression, insert a backslash. No special meaning." However, in Java, "\ \", I mean "I want to insert it is an expression of the backslash, with the back of it that the meaning of the characters changed. "For example, if you would like to say one or more of the" character word, "Well, this is the regular expression should be "\ \ w +." If you want to insert a backslash, then to use "\ \ \ \." But like other firms, such as tabbing or only a backslash: "\ n \ t."
Only speaking to you here an example you should document java.util.regex.Pattern JDK Add Bookmark, so it should be easy to find a regular expression pattern has.
Logical XYX followed YX | YX or Y (X) "to match the group (capturing group)." Can be used after the \ i said to be the i-matched group.
Matching the border at the beginning of his $ ^ at the end of his \ b a word boundary \ B, a non-word boundary \ G before the end of a match
Cite a specific example. Below are the expression of these are legitimate, and can match "Rudolph":
Rudolph [rR rR] udolph [] [aeiou] [az] R. ol .* *
Fu said that the number of
"Fu said that the number of (quantifier)" is the definition of the role model should match the number of characters.
- Greedy (greedy): Unless otherwise indicated, or that the number of the greedy at all. Greedy expression has been matched continue until the match does not go so far. (If you find expression matching with the expected results not), most likely because you think that expression will only match in front of several characters, and in reality it is greedy, so it will always match.
- Reluctant (barely): The question indicated that it would at least match the characters. Also known as lazy, minimal matching, non-greedy, or ungreedy.
- Possessive (possession): The only Java support (other languages do not support). It has more advanced, so you may also not be used. As a regular expression matching string will be a lot of intermediate state, (general matching engine will preserve this intermediate state), when the failure of this match will be returned to the Yuan. Possession of expression do not save this intermediate state, therefore, you will not go back to the weight. It is then to prevent the uncontrolled expression, but also to improve operational efficiency.
Greedy Reluctant Possessive matching X - X - X? + Matching one or zero-XX * X *? X * + match zero or more than X X + X +? X + + matching one or more X XX (n) (n)? X (n) + n-XX match precisely (n, n (X),)? X (n, n) + match at least a XX (n, m) X (n, m)? X (n, m) + match n at least, up to the m X
To remind, to get expressions as you mean to run, you should use square brackets to 'X' enclose. For example:
Abc +
It seems that this expression to match one or several 'abc', but if you really use it to match 'abcabcabc', in fact only find three characters. Because the meaning of this expression is' ab 'behind with one or more of the' c '. To match one or more of a complete 'abc', you should be this:
(Abc) +
The regular expression can easily take you to play; This is a built on the new Java language.
CharSequence
JDK 1.4 defines a new interface, called CharSequence. It provides a String and StringBuffer these two categories of the characters in the sequence of abstract:
Interface CharSequence (charAt (int i); length (); subSequence (int start, int end); toString ();)
In order to achieve this new CharSequence interface, String, as well as CharBuffer StringBuffer have been modified. Regular expressions are a lot of operational parameters to be with CharSequence.
Pattern and Matcher
先给an example. The following procedures to test whether a regular expression matching string. The first parameter is the string to match, followed by the regular expression. Regular expressions can have more than one. Unix / Linux environment, a command line under the regular expression must also be used in quotation marks.
When you create a regular expression, you can use this procedure to judge it is not in accordance with the requirements of your work.
/ /: C12: TestRegularExpression.java / / Allows you to easly try out regular expressions / / (Args: abcabcabcdefabc "abc +" "(abc) +" "(abc) (2)") import java.util.regex .*; public class TestRegularExpression (public static void main (String [] args) (if (args.length <2) (System.out.println ( "Usage: \ n" + "java TestRegularExpression" + "characterSequence regularExpression +") ; System.exit (0);) System.out.println ( "Input: \" "+ args [0] +" \ "") for (int i = 1; i <args.length; i + +) (System . out.println ( "Regular expression: \" "+ args [i] +" \ ""); Pattern p = Pattern.compile (args [i]); Matcher m = p.matcher (args [0]); while (m.find ()) (System.out.println ( "Match \" "+ m.group () +" \ "at positions" m.start + () + "-" + (m.end () — 1));)))) ///:~
Java's regular expressions by the java.util.regex Pattern Matcher class and achievable. Pattern said that the object of a regular expression compiler. Static compile () method that will be responsible for a regular expression string compiled into Pattern object. As shown in the above routines, as long as the matcher to the Pattern () method to send a string object will be able to access a Matcher. In addition, there is a Pattern to quickly determine whether the input found inside the regex (Note that the original error, and missed the method)
Static boolean matches (regex, input)
String arrays, as well as to return to the split () method, it can use regex separated from the string.
As long as the Pattern.matcher () method-will be able to gain a string of Matcher object. Next Matcher method can be used to match the results of the enquiry.
Boolean matches () boolean lookingAt () boolean find () boolean find (int start)
Matches () Pattern Matching is the premise of the entire string, and lookingAt () Pattern Matching is the meaning of the beginning of the string.
Find ()
Matcher.find () function is found CharSequence Lane, and a number of pattern matching sequences of characters. For example:
/ /: C12: FindDemo.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; import java.util .*; public class FindDemo (private static Test monitor = new Test (); public static void main (String [] args) (Pattern.compile Matcher m = ( "\ \ w +"). matcher ( "Evening is full of the linnet's wings"); while (m.find ()) System.out.println (m. group ()); int i = 0; while (m.find (i)) (System.out.print (m.group () + "") i + +;) monitor.expect (new String [] ( "Evening "," is "," full "," of "and" the "and" linnet "," s "and" wings "," Evening vening ening ning ing ng g is is s full "+" full ull ll l of of f the the he e linnet linnet "+" innet nnet net et tss wings wings ings ngs gs s "));)) ///:~
"\ \ W +" means "one or more characters in the word", it will be decomposed into direct word string. Find () as an iteration, again from start to finish scanning string. The second find () int parameters of the zone, as you can see, it will start to tell where to find methods - from the beginning View location parameters.
Groups
Group refers to enclose, with the brackets, the following expression can be called a regular expression. Group 0 that the whole pattern, a group that was the first to include the group, and so on. Therefore;
A (B (C)) D
There are three group: group 0 is ABCD, a group is BC, is the C group 2.
You can use the following method to use Matcher group:
Public int groupCount () returns matcher in the target group number. Excluding group0.
Public String group () returns the last match operations (for example, find ()) group 0 (the entire match)
Public String group (int i) return to the operation of the last match of a group. If successful match, but failed to find a group, then returned to the null.
Public int start (int group) to return to the last match found, the group started here.
Public int end (int group) to return to find the last match, the end position group, the last subscript characters plus one.
Below we give some examples of the group:
/ /: C12: Groups.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; public class Groups (private static Test monitor = new Test (); static public final String poem = "Twas brillig, and the slithy toves \ n "+" Did gyre and gimble in the wabe \ n "+" All mimsy were the borogoves, \ n "+" And the mome raths outgrabe \ n \ n "+" Beware the Jabberwock, my son, \ n "+" The jaws that bite, the claws that catch \ n "+" Beware the Jubjub bird, and shun \ n "+" The frumious Bandersnatch. "; public static void main (String [] args) Pattern.compile Matcher m = (( "(? m) (\ \ S +) \ \ s + ((\ \ S +) \ \ s + (\ \ S +))$"). matcher (poem); while (m.find ()) (for (int j = 0; j <= m.groupCount (); j + +) System.out.print ( "[" + m.group (j) + "]"); System.out.println ( );) monitor.expect (new String [] ( "[the slithy toves]" + "[the slithy toves] [] [] [slithy toves]", "[in the wabe.] [] [in the wabe. ] [] [the wabe.] "," [were the borogoves,] "+" [were] [the borogoves,] [the] [borogoves,] "," [mome raths outgrabe.] "+" [mome] [raths outgrabe.] [] [raths outgrabe.] "," [Jabberwock, my son,] "+" [Jabberwock, my son] [] [] [my son], "" [claws that catch.] "+" [claws that catch] [] [] [catch that.] "," [bird, and shun] [bird, and shun] [] [and] [shun] "," [The frumious Bandersnatch.] [The] "+" [frumious Bandersnatch.] [] [frumious Bandersnatch.] "));)) ///:~
This poem is Through the Looking Glass, Lewis Carroll's "Jabberwocky" to the first part. Can see that this is a lot of regular expressions, including parentheses together with the group, it is by any number of consecutive non-space characters ( '\ S +') and any number of continuous space characters ( '\ s +') formed, with the ultimate aim is to capture each on the final three words; '$' to the end of that line. But '$' are usually stated at the end of the string, so here clearly told a regular expression attention to the newline. This is from '(? M)' signs completed (mode markers Guoyihui on).
Start () and end ()
If successful match, the start () will return to the beginning of the match position, end () will return to the position of the end of this match, the final one of the characters and a subscript. If unsuccessful before the match (or did not match), then either call the start () or end (), will trigger a IllegalStateException. Below this procedure also demonstrated matches () and lookingAt ():
/ /: C12: StartEnd.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; public class StartEnd (private static Test monitor = new Test (); public static void main (String [] args) ( String input [] = new String [] ( "Java has regular expressions in 1.4", "regular expressions now expressing in Java," "Java represses oracular expressions"); Pattern p1 = Pattern.compile ( "re \ \ w *" ), p2 = Pattern.compile ( "Java .*"); for (int i = 0; i <input.length; i + +) (System.out.println (" input "+ i +": "+ input [i ]); Matcher m1 = p1.matcher (input [i]), m2 = p2.matcher (input [i]); while (m1.find ()) System.out.println ( "m1.find (), '" m1.group + () + " 'start =" + m1.start () + "end =" + m1.end ()); while (m2.find ()) System.out.println ( "m2.find ( ) ' "+ m2.group () +"' start = "+ m2.start () +" end = "+ m2.end ()); if (m1.lookingAt ()) / / No reset () necessary System . out.println ( "m1.lookingAt () start =" + m1.start () + "end =" + m1.end ()); if (m2.lookingAt ()) System.out.println ( "m2. lookingAt () start = "+ m2.start () +" end = "+ m2.end ()); if (m1.matches ()) / / No reset () necessary System.out.println (" m1.matches () start = "+ m1.start () +" end = "+ m1.end ()); if (m2.matches ()) System.out.println (" m2.matches () start = "+ m2. start () + "end =" + m2.end ());) monitor.expect (new String [] ( "input 0: Java has regular expressions in 1.4", "m1.find () 'regular' start = 9 end = 16 "," m1.find () 'ressions' end start = 20 = 28 "," m2.find ()' Java has regular expressions in 1.4 ' "+" end start = 0 = 35 "," m2. lookingAt () start = 0 end = 35 "," m2.matches () start = 0 end = 35 "," input 1: regular expressions now "+" expressing in Java, "" m1.find () 'regular' start end = 0 = 7 "," m1.find () 'ressions' end start = 11 = 19 "," m1.find ()' ressing 'end start = 27 = 34 "," m2.find ()' Java ' start = 38 = 42 end "," m1.lookingAt () start = 0 end = 7 "," input 2: Java represses oracular expressions, "" m1.find () 'represses' end start = 5 = 14, "" m1.find () 'ressions' end start = 27 = 35 "," m2.find ()' Java represses oracular expressions' "+" end start = 0 = 35 "," m2.lookingAt () = start = 0 end 35, "" m2.matches () start = 0 end = 35 "));)) ///:~
Attention, as long as there are strings in this model, find () will be able to find it out, but lookingAt () and matches (), only in a regular expression string and the beginning of a match, which can be returned to the true. Matches () is the prerequisite for the success of a regular expression and a string perfectly matched, and lookingAt () [67] success on the premise that with the beginning of a string of a regular expression matching.
Matching mode (Pattern flags)
Compile () method is also available in a version, it needs a control is the regular expression matching of parameters:
Pattern Pattern.compile (String regex, int flag)
The value of the flag as follows: compiler signs Pattern.CANON_EQ effect if and only when the two characters "regular decomposition (canonical decomposition)," are exactly the same circumstances, it finds that match. For example, after using this symbol, in the expression "a \ u030A" will match "?." Default situation, we do not consider "the same norms (canonical equivalence)." Pattern.CASE_INSENSITIVE
(? I) default, unknown flu case matching only applies to US-ASCII character sets. The logo can neglect case expression matching. To the Unicode characters matching sense of unknown size, as long as the signs and will UNICODE_CASE together on the trip. Pattern.COMMENTS
(? X) In this mode, when the match will be overlooked (in the regular expression) space characters (Translator note: not the expression of the "\ \ s", but that the expression in space , tab, carriage return of the category). # Notes from the beginning until the end of this trip. Can be embedded to mark the opening of Unix mode. Pattern.DOTALL
(? S) in this mode, the expression '.' Can match any of the characters, including that at the end of his party. By default, the expression '.' Mismatch at the end of the trip. Pattern.MULTILINE
(? M) In this mode, '^' and '$', respectively match and the beginning of his end. In addition, the '^' still match the beginning of a string, '$' the end of the string also matched. By default, these two expressions matched only the beginning and the end of the string. Pattern.UNICODE_CASE
(? U) in this mode, if you have opened CASE_INSENSITIVE signs, then it will Unicode characters unknown flu case matching. By default, unknown flu case matching only applies to US-ASCII character sets. Pattern.UNIX_LINES
(? D) In this mode, the only '\ n'æ‰è¢«recognition for his suspension, and with'.','^', as well as' $ 'match.
In these signs inside, Pattern.CASE_INSENSITIVE, Pattern.MULTILINE, is the most useful and Pattern.COMMENTS (which Pattern.COMMENTS also help us to clarify ideas, and / or doing documentation). Note that you can use in the expression inserted in the way to mark the opening of the majority of the models. These marks in the table aboveé‚£å¼ all signs below. Mode where you want to start, where interpolation mark.
Can be used "OR" ('|') operator of the use of these signs:
/ /: C12: ReFlags.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; public class ReFlags (private static Test monitor = new Test (); public static void main (String [] args) ( Pattern p = Pattern.compile ( "^ java," Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); Matcher m = p.matcher ( "java has regex \ nJava has regex \ n" + "JAVA has pretty good regular expressions \ n" + "Regular expressions are in Java"); while (m.find ()) System.out.println (m.group ()); monitor.expect (new String [] ( "java", "Java", "JAVA "));)) ///:~
This created by the regular expression will match "java", "Java", "JAVA" … the beginning of the string. In addition, if the strings at several firms, which it will do on each match (matching sequences of characters at the beginning, and finally sequences of characters at the end of the trip). Note that group () method to return only part of the match.
Split ()
Refers to the so-called segmentation will be a regular expression for the sector, will be split into String string array.
String [] split (CharSequence charseq) String [] split (CharSequence charseq, int limit)
This is a fast and easy text according to some of the common border to sign separate ways.
/ /: C12: SplitDemo.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; import java.util .*; public class SplitDemo (private static Test monitor = new Test (); public static void main (String [] args) (String input = "This! unusual use! of exclamation! points"; System.out.println (Arrays.asList (Pattern.compile ("!!"). split (input)) ); / / Only do the first three: System.out.println (Arrays.asList (Pattern.compile ("!!"). split (input, 3))); System.out.println (Arrays.asList ( " Aha! String has a split () built in!. "split (" "))); monitor.expect (new String [] ( "[This, unusual use, of exclamation, points]", "[This, unusual use , of exclamation! points] "," [Aha!, String, has a, split (), built, in!] "));)) ///:~
The second split () will limit the number of segmentation.
The regular expression is so important, so some features were incorporated into String class, including split () (have seen), and matches (), replaceFirst (), as well as replaceAll (). With the function of these methods Pattern Matcher and the same.
Replacement Operation
Regular expressions are particularly expert replacement text. Here are some ways:
ReplaceFirst (String replacement) string, and the first model of the match in the replace string replacement.
ReplaceAll (String replacement), all the input string, and the match in the model replace all string replacement.
AppendReplacement (StringBuffer sbuf, String replacement) on successive sbuf to replace, rather than replaceFirst () or replaceAll (), the replacement of only one or all of string. This is a very important, because it can call methods to generate replacement (replaceFirst () and replaceAll () only permits the use of fixed strings to act as replacement). With this method, you can distinguish between programming group in order to achieve more powerful replacement function.
Calling End appendReplacement (), in order to return the remaining copies of the string, we must call appendTail (StringBuffer sbuf, String replacement).
Below us to a demonstration of how to use these substitutions. Elaborate, this procedure is handled by its own string beginning of the Notes is the use of regular expressions is extracted and be dealt with after transmission replacement method.
/ /: C12: TheReplacements.javaimport java.util.regex .*; import java.io. *; import com.bruceeckel.util .*; import com.bruceeckel.simpletest .*;/*! Here's a block of text to use as input to the regular expression matcher. Note that we'll first extract the block of text by looking for the special delimiters, and then process the extracted block.! * / public class TheReplacements (private static Test monitor = new Test (); public static void main (String [] args) throws Exception (String s = TextFile.read ( "TheReplacements.java"); / / Match the specially-commented block of text above: Matcher mInput = Pattern.compile ( "/ \ \ *!(.*)! \ \ * / ", Pattern.DOTALL). matcher (s); if (mInput.find ()) s = mInput.group (1); / / Captured by parentheses / / Replace two or more spaces with a single space: s = s.replaceAll ( "(2)", "") / / Replace one or more spaces at the beginning of each / / line with no spaces. Must enable MULTILINE mode: s = s.replaceAll ( "(? m) ^ +", ""); System.out.println (s) s = s.replaceFirst ( "[aeiou]", "(VOWEL1)") = new StringBuffer StringBuffer sbuf (); Pattern p = Pattern.compile ( "[aeiou]"); Matcher m = p.matcher (s) / / Process the find information as you / / perform the replacements: while (m.find ()) m . appendReplacement (sbuf, m.group (). toUpperCase ()) / / Put in the remainder of the text: m.appendTail (sbuf); System.out.println (sbuf); monitor.expect (new String [] ( "Here's a block of text to use as input to," and "the regular expression matcher. Note that we'll", "first extract the block of text by looking for", "the special delimiters, and then process the," " extracted block. "," H (VOWEL1) rE's A blOck Of tExt tO UsE As InpUt tO "," thE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE'll "," fIrst ExtrAct thE blOck Of tExt by lOOkIng fOr "," thE spEcIAl dElImItErs, thEn prOcEss thE "," ExtrActEd blOck. "));)) ///:~
We introduced by the previous TextFile.read () method to open and read documents. MInput function is'/*!' and'!*/' match between the text (to the attention of the group with brackets). Next, we will all more than two consecutive spaces all as a replacement, and the trip will be the beginning of the space are removed (this is to allow the expression of the will of all firms, not just the first line work, Multi-line must be enabled). These two operations are used String of replaceAll () (more convenient to use it here). Attention, as each replacement only once, in addition to pre-compiler Pattern Therefore, no additional procedures expenses.
ReplaceFirst () only the first sub-string replacement. In addition, replaceFirst () and replaceAll () can only constants (literal) to replace, so if you replace each time to carry out some operation, they are powerless. Encountered such a situation, to use your appendReplacement (), which enables you to replace the time to write in the number of written code number. During that in the above procedures, the process of creating sbuf to deal with the elected group, which is a regular expression with the vowel letters find out, and then changed the course of capital. Usually you have completed all of the replacement after calling appendTail (), but if we imitate replaceFirst () (or "replace n") effects, you can only call on a replacement appendTail (). It would put all things remaining sbuf.
You can also appendReplacement () replacement parameters, "$ g" quoted the group has been arrested, 'g' group said the number. But this is to prepare the operation is relatively simple and, therefore, its effect can not be compared with the above-mentioned procedures.
Reset ()
In addition, it can be reset () method to existing Matcher object accompanied by new CharSequence.
/ /: C12: Resetting.javaimport java.util.regex .*; import java.io. *; import com.bruceeckel.simpletest .*; public class Resetting (private static Test monitor = new Test (); public static void main (String [] args) throws Exception (Matcher m = Pattern.compile ( "[] [aiu frb gx] []"). matcher ( "fix the rug with bags"); while (m.find ()) System. out.println (m.group ()); m.reset ( "fix the rig with rags"); while (m.find ()) System.out.println (m.group ()); monitor.expect (new String [] ( "fix", "rug," "bag", "fix" and "rig", "rag"));)) ///:~
If we fail to give parameters, reset () will be set up to the current Matcher at the beginning of the string.
Regular Expression and Java I / O
So far, all you see with a regular expression handling static string example. Below us to a demonstration of how to use a regular expression matching scanned documents and find the string. Inspired by the Unix grep, I wrote a JGrep.java, it requires two parameters: the file name, as well as the matching string with a regular expression. It will match a regular expression that this part of the trip and its affiliated firms, print it.
/ /: C12: JGrep.java / / A very simple version of the "grep" program / / (Args: JGrep.java "\ \ b [Ssct] \ \ w +") import java.io. *; import java . util.regex .*; import java.util .*; import com.bruceeckel.util .*; public class JGrep (public static void main (String [] args) throws Exception (if (args.length <2) (System . out.println ( "Usage: java JGrep file regex"); System.exit (0);) Pattern p = Pattern.compile (args [1]); / / Iterate through the lines of the input file: ListIterator it = new TextFile (args [0]). listIterator (); while (it.hasNext ()) (p.matcher Matcher m = ((String) it.next ()); while (m.find ()) System.out . println (it.nextIndex () + ":" + m.group () + ":" + m.start ());))) ///:~
Document is opened using TextFile (the first part of this chapter stresses). As TextFile will document the trip on ArrayList inside, and we extract a ListIterator, so we can document the trip in which freedom of movement (both can also move backward).
Each row will have a Matcher, then find () scan. Note that we use ListIterator.nextIndex (), line tracking.
Test parameters are JGrep.java and [Ssct] the beginning of the word.
StringTokenizer need?
See the regular expression can provide such a powerful function, you might suspect, is not also need the original StringTokenizer. JDK 1.4 previously, in order to split the string, with only StringTokenizer. But now, with a regular expression, the more it can do the clean and agile.
/ /: C12: ReplacingStringTokenizer.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; import java.util .*; public class ReplacingStringTokenizer (private static Test monitor = new Test (); public static void main (String [] args) (String input = "But I'm not dead yet! I feel happy!"; StringTokenizer stoke = new StringTokenizer (input), while (stoke.hasMoreElements ()) System.out.println (stoke. nextToken ()); System.out.println (Arrays.asList (input.split ( ""))); monitor.expect (new String [] (" But "," I'm "," not "," dead , "" yet! "," I "," feel "," happy "," [But, I'm, not, dead, yet!, I, feel, happy!] "));)) / / /: ~
With the regular expression, you can use more complex models will be separated from the string - to StringTokenizer If so, things will be much more trouble. I can be very confident that the regular expression can replace StringTokenizer.
To further study the regular expression, I suggest you look at Mastering Regular Expression, 2nd Edition, the author Jeffrey EF Friedl (O'Reilly, 2002).
Aggregate
Java I / O stream class library should be able to meet your basic needs: you can use it to read and write the console, documentation, memory, and even Internet. You can also use the inheritance to create new input and output types. You can even use the Java objects will automatically call the toString () method of characteristics (Java only the "automatic conversion"), through the re-definition of this method to pass on to the target flow to a simple expansion.
But Java's I / O libraries and documentation flow or left some deficiencies. For example, you open a file往里é¢write things, but the document has been published, the original will do to the content of the coverage. Then if anomalies like to have a - some programming language allows you only to the provisions of the new document output. Java appears to File object you use to judge whether the document exists, because if you use FileOutputStream FileWriter or so, the paper will be covered.
I I / O stream class library evaluation is a contradiction that it is capable lot of things, and do the cross-platform. But if you do not know decorator mode, it will find this design too difficult to understand, so regardless of the teachers or students, have spent much energy. In addition the class library is complete, otherwise, I also do not need to write a TextFile. In addition, it did not provide formatted output functions, and other languages have been provided this capability.
However, if you really understand the decorator patterns, and to begin flexibility in the use of this class library, you can feel the benefits of this design. Then write a few more lines of code on a nothing.
If you feel thirsty (just to be a of this chapter, thought to be exhaustive), and look at Elliotte Rusty Harold write Java I / O (O'Reilly, 1999). This book put it deeper.
Tags: examples, Regular Expression






