core java 따라하기 - 2
2017. 6. 15. 11:25ㆍJava
지난번에 이어서.. .계속..
SECTION 11. Regular Expressions
Common Tasks
String[] words = str.split("\\s+"); | Split a string along white space boundaries. 공백 경계를 기점으로 문자열을 쪼개다. |
Pattern pattern = Pattern.compile("[0-9]+"); Matcher matcher = pattern.matcher(str); String result = matcher.replaceAll("#"); | Replace all matches. Here we replace all digit sequences with a #. 매칭한 모든것을 바꿉니다. 모든 연속된 숫자를 # 으로 변경합니다. (혹시 하나씩 변경하려면, [0-9]+ 에서 +를 제거) |
Pattern pattern = Pattern.compile("[0-9]+"); Matcher matcher = pattern.matcher(str); while(matcher.find()){ process(str.substring(matcher.start(), matcher.end())); } | Find all matches. 매치되는 모든 걸 찾아준답니다. |
Pattern patern = Pattern.compile("(1?[0-9]):([0-5][0-9])[ap]m"); Matcher matcher = pattern.matcher(str); for(int i =0 ; i < matcher.groupCount(); i++){ process(matcher.group(i)); } | Find all groups(indicated by parentheses in the pattern). Here we find the hours and minutes in a date. 모든 그룹들을 찾습니다.(패턴내의 괄호들에 의해 가르킨) 여기에서는 날짜의 시간과 분을 찾습니다. |
Regular Expression Syntax
Characters
c | The character c |
\unnnn, \xnn , \on , \onn, \onnn | The code unit with the given hex or octal value 주어진 16진수 혹은 8진수 값을 가진 코드 단위 |
\t, \n, \r, \f, \a , \e | The control characters tab, newline, return , form feed, alert, and escape. 탭, 줄바꿈,리턴, 폼 피드, 알람, esc |
\cc | The control character corresponding to the character c C 문자열에 일치하는 컨트롤 문자 |
Character Classes
[C1C2...] | Union: Any of the characters represented by C1C2.... The Ci are characters, character ranges c1-c2, or character classes. Exampe:[a-zA-Zo-9_] C1C2으로 표시되는 문자열들. Ci은 문자열들, 문자 범위는 c1-c2 또는 문자 클래스들. |
[^C1C2...] | Complement : Characters not represented by any of C1C2... Example:[^0-9] C1C2로 표시되지 않는 문자열 |
[C1&&C2 &&..] | Intersection: Characters represented by all C1C2... Example: [A-f&&[^C-']] C1,C2 모두 표시되는 문자열들 |
Predefined Character Classes
. | Any character except line terminators(or any character if the DOTALL flag is set) 라인 종결자를 제외한 모든 문자(또는 DOTALL 표기가 되었을때 문자) |
\d | A digit [0-9] |
\D | A nondigit [^0-9] |
\s | A whitespace character [ \t\n\r\f\xoB ] |
\S | A nonwhitespace character |
\w | A word character [a-zA-Z0-9_] |
\W | A nonword character |
\p{name} | A named character class-see table below |
\P{name} | The complement of a named character class |
Boundary Matchers
^$ | Begining, end of input(or begining, end of line in multiline mode) |
\b | A word boundary |
\B | A nonword boundary |
\A | Begining of input |
\z | End of input |
\Z | End of input except final line terminator |
\G | End of previous match |
Quantifiers
X? | Optional X |
X* | X, 0 or more times |
X+ | X, 1 or more times |
X{n}X{n,}X{n,m} | X n times, at least n times, between n and m times |
Quantifier Suffixes
? | Turn default (greedy) match into reluctant match 기본 매치를 맘에 안드는 매치로 바꾸다 |
+ | Turn default(greedy) match into reluctant match |
Set Operations
XY | Any string from X, followed by any string from Y X의 모든 문자열 다음에 Y의 문자열 |
X|Y | Any string from X or Y X나 Y의 모든 문자열 |
Grouping
(X) | Capture the string matching X as a group |
\g | The match of the gth group |
Escapes
\c | The character c (must not be an alphabetic character) |
\Q....\E | Quote ... verbatim |
(?...) | Special construct-see API notes of Pattern class |
Predefined Character Class Names
Lower | ASCII lower case [a-z] |
Upper | ASCII upper case [A-Z] |
Alpha | ASCII alphabetic [A-Za-z] |
Digit | ASCII digits [0-9] |
Alnum | ASCII alphabetic or digit [A-Za-z0-9] |
XDigit | Hex digits[0-9A-Fa-f] |
Print or Graph | Printable ASCII character [\x21-\x7E] |
Punct | ASCII nonalpha or digit [\p{Print}&&\PPalnum}] |
ASCII | All ASCII [\x00-\x7F] |
Cntrl | ASCII Control character [\x00-\x1F] |
Blank | Space or tab[\t] |
Space | Whitespace [\t\n\r\f\0x0B] |
javaLowerCase | Lower case, as determined by Character.isLowerCase() |
javaUpperCase | Upper case, as determined by Character.isUpperCase() |
javaWhitespace | White space, as determined by Character.isWhitespace() |
javaMirrored | Mirrored, as determined by Character.isMirrored() |
InBlock | Block is the name of a Unicode character block, with spaces removed, such as BasicLatin or Mongolian. |
Category or InCategory | Category is the name of a Unicode character category such as L(letter) or Sc(currency symbol) |
Flags for Matching
패턴 매칭하는 것을 플래그를 사용해서 조절할수 있습니다.
The pattern matching can be adjusted with flags, for example
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE + Pattern.UNICODE_CASE) |
FLAG | Description |
CASE_INSENSITIVE | Match characters independently of the letter case. By default, this flag takes only US ASCII characters into account 대문자와 독립적인 문자열을 매칭합니다. 기본적으로, 이 플래그는 US ASCII 문자열들만 고려합니다. |
UNICODE_CASE | When used in combination with CASE_INSENSITIVE, use Unicode letter case for matching CASE_INSENSITIVE와 함께 사용될때, 매칭을 위해 Unicode 대문자를 사용합니다. |
MULTILINE | ^ and $ match the begining and end of a line, not the entire input ^와$는 전체 입력이 아니고 라인의 시작과 끝을 매칭합니다. |
UNIX_LINES | Only '\n\' is recognized as a line terminator when matching ^ and $ in multiline mode 멀티라인 모드상에서 ^과 $를 매칭할때 오직 \n 를 라인종결자로 나타냅니다. |
DOTALL | When using this flag, the . symbol matches all characters, including line terminators 이 플래그를 사용하면, . 심볼은 모든 문자열을 매칭합니다 라인 종결자들을 포함해서 |
CANON_EQ | Takes canonical equivalence of Unicode characters into account. For example, u followed by "(diaeresis) matches ü 유니코드 문자열들의 표준 동등성을 고려합니다. 예를 들어, u 다음에 " 은 와 ü 일치합니다. |
LITERAL | The input string that specifies the pattern is treated as a sequence of literal characters, without special meanings for .[] etc. 패턴이 명시된 입력문자는 일련의 글자 그대로의 문자열로 다뤄집니다. .[]등과 같이 특정한 의미가 없이.. |
SECTION 12 Logging
Common Tasks
Logger logger = Logger.getLogger("com.mycompany.myprog.mycategory"); | Get a logger for a category 카테고리에 대한 로거를 얻습니다. |
logger.info("Connection successful."); | Logs a message of level FINE. Available levels are SEVERS, WARNING, INFO, CONFIG, FINE, FINER, FINEST, with corresponding methods severe, warning and so on. FINE 레벨의 메시지를 로깅합니다. 이용가능한 레벨은 server,warning등등의 일치하는 메소드들을 갖는SEVERS, WARNING, INFO, CONFIG, FINE, FINER, FINEST 입니다. |
logger.log(Level.SEVERE, "Unexpected exception", Throwable); | Logs the stack trace of a Throwable. 예외로던져진 스택 추적을 로그 합니다. |
logger.setLevel(Level.FINE); | Sets the logging level to FINE. By default, the logging level is INFO, and less severe logging messages are not logged. 로깅 레벨을 FINE으로 맞춥니다. 기본으로, 로깅레벨은 INFO이고, severe보다 적은 로깅 메시지는 로깅하지 않습니다. |
Handler handler = new FileHandler("%h/myapp.log", SIZE_LIMIT, LOG_ROTATION_COUNT); handler.setFormatter(new SimpleFormatter(); logger.addHandler(handler); | Add a file handler for saving the log records in a file. See the table below for the naming pattern. This handler uses a simple formatter instead of the XML formatter that is the default for file handlers. 한 파일에 로그 기록들을 저장하기 위해서 파일 핸들러를 추가합니다. 패턴 네이밍을 위해 아래 테이블을 보세요. 이 핸들러는 파일 핸들러들을 위해 기본으로 되어 있는 XML 포멧터 대신에 단순 포맷터를 사용합니다. |
Logging Configuration Files
The logging configuration can be configured through a logging configuration file, by default "jre/lib/logging.properties".
Another file can be specified with system property "java.util.logging.config.file" when starting the virtual machine.
(Note that the LogManager runs before main.)
로깅 설정은 기본으로 "jre/lib/logging.properties", 로깅 설정 파일을 통해 설정할수 있습니다.
가상머신을 구동할 때,"java.util.logging.config.file" 시스템 프로퍼티을 가지고 다른 파일 명시할수 있습니다.
(LogManager는 main 전에 구동합니다.)
CONFIGURATION PROPERTY | DESCRIPTION | DEFAULT |
loggerName.level | The logging level of the logger by the given name | None; the logger inherits the handler from its parent. |
handler | A whitespace or comma-separated list of class names for the root logger. An instance is created for each class name, using the default constructor | java.util.logging.ConsoleHandler |
loggerName.handlers | A whilespace or comma-separated list of class names for the given logger | list of class names for the given logger None |
loggerName.usePatternHandlers | false if the parent logger's handler(and ultimately the root logger's handlers) should not be used | true |
config | A whitespace or comma-separted list of class names for initialization | None |
java.util.logging.FileHandler.level java.util.logging.ConsoleHandler.level | The default handler level | Level.ALL for FileHandler, Level.INFO for ConsoleHandler |
java.util.logging.FileHandler.filter java.util.logging.ConsoleHandler.filter | The class name of the default filter | None |
java.util.logging.FileHandler.formatter java.util.logging.ConsoleHandler.formatter | The class name of the default filter | formatter java.util.logging.XMLFormatter for FileHandler, java.util.logging.simpleFormatter for ConsoleHandler |
java.util.logging.FileHandler.encoding java.util.logging.ConsoleHandler.encoding | The default encoding | default platform encoding |
java.util.logging.FileHandler.limit | The default limit for rotating log files, in bytes | 0(No limit), but set to 50000 in jre/lib/ logging.properties |
java.util.logging.FileHandler.count | The default number of rotated log files | 1 |
java.util.logging.FileHandler.pattern | The default naming pattern for log files. The following tokens are replaced when the file is created: - / : path separator %t : System temporary directory %h : Value of user.home system property %g : The generation number of rotated logs %u : A unique number for resolving naming conflicts %% : The % character | %h/java%u.log |
java.util.logging.FileHandler.apped | The default append mode for file loggers; true to append to an existing log file | false |
SECTION 13 Property Files
- =,: 또는 공백으로 구분되어진 이름과값으로 쌍으로 구성합니다.
- 이름주변에 공백 또는 값이 시작전에 공백은 무시됩니다.
- n 라인을 마지막 문자로 \ 을 놓는 것으로 연결할수 있습니다. 연속된 줄에 공백이 오는 것은 무시됩니다.
- \t \n \f \r \\ \uxxxx escapes 는 인식됩니다 ( 하지만 \b 또는 8진수 이스케프는 아닙니다)
- 파일들은 ISO 8859-1로 인코딩된 것으로 간주합니다. :
- 공백 라인과 #,!로 시작하는 라인은 무시됩니다.
- Contain name/value pairs, separated by =,:, or whitespace.
- Whitespace around the name or before the start of the value is ignored
- n Lines can be continued by placing an \ as the last character; leading whitespace on the continuation line is ignored
button1.tooltip = This is a long \ tooltip text. |
- \t \n \f \r \\ \uxxxx escapes are recognized ( but not \b or octal escapes)
- Files are assumed to be encoded in ISO 8859-1; use natvie2ascii to encode non-ASCII characters into Unicode escapes
- Blank lines and lines starting with # or ! are ignored
Typical Usage:
Properties props = new Properties(); props.load(new FileInputStream("prog.properties")); String value = props.getProperty("button1.tooltip"); //null if not present |
Also Used for Resource Bundles :
ResourceBundle bundle = ResourceBundle.getBundle("prog"); // Searches for prog_en_US.properties, // prog_en.properties, etx String value = bundle.getString("button1.tooltip"); |
SECTION 14 JAR Files
- 응용프로그램 코드 라이브러리 저장에 사용됩니다.
- 기본으로 클래스 파일들과 다른 리소스 파일들이 Zip 파일 형태로 저장됩니다.
- META-INF/MANIFEST.MF는 JAR metadata를 포함합니다.
- META-INF/services 은 서비스 제공자 설정을 포함할수 있습니다.
- jar 파일들을 표기하기 위해 jar 유틸리티를 사용하세요
- Used for storing applications, code libraries
- By default, class files and other resources are stored in ZIP file format
- META-INF/MANIFEST.MF contains JAR metadata
- META-INF/services can contain service provider configuration
- Use the jar utillity to mark jar files
JAR Utiltity Options
OPTION | DESCRIPTION |
c | Creates a new or empty archive and adds files to it. If any of the specified file names are directories, the jar program precesses them recursively. |
C | Temporarily changes the directory. For example, jar cvfC myprog.jar classes *.class change to the classes subdirectory to add class files |
e | Create a Main-Class entry in the manifest jar cvfe myprog.jar com.mycom.mypkg.MainClass files |
f | Specifies the JAR file name as the second command-line argument. If this parameter is missing, jar will write the result to standard output(when creating a JAR file) or read it from standard input(when extracting or tabulating a JAR file) |
i | Create an index file (for speeding up lookups in a large archive) |
m | Adds a manifest to the JAR file.jar cvfm myprog.jar mymanifest.mf files |
M | Does not create a manifest file for the entries |
t | Displays the table of contents.jar tvf myprog.jar |
u | Updtes an existing JAR file jar uf myprog.jar com/mycom/mypkg/SomeClass.class |
v | Generates verbose output |
x | Extracts files. If you supply one or more files names, only those files are extracted. Otherwise, all files are extracted. jar xf myprog.jar |
O | Stores without ZIP compression |
SECTION 15. Common javac Options
OPTION | PURPOSE |
-cp or -classpath | Sets the class path, used to search for class files. The class path is a list of directories, JAR files, or expressions of the form directory/'*' (Unix) or directory\* (Windows). The latter refers to all JAR files in the given directory. Class path items are separated by : (Unix) or ; (Windows). If no class path is specified, it is set to the current directory. If a class path is specified, the current directory is not automatically included-add a . item if you want to include it |
-sourcepath | Sets the path used to search for source files. If source and class files are present for a given file, the source is compiled if it is newer. If no source path is specified, it is set to the current directory |
-d | Sets the path used to place the class files. Use this option to separate .java and .class files |
-source | Sets the source level. Valid values are 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 5, 6, 7, 8 |
-deprecation | Gives detail information about the use of deprecated features |
-Xlint:unchecked | Gives detail information about unchecked type conversion warnings |
-cp or -classpath | Sets the class path, used to search for class files. See the previous table for details. Note that javac can succeed when java fails if the current directory is on the source path but not the class path. |
-ea or enableassertions | Enable assertions. By default, assertions are disabled. |
-Dproperty=value | Sets a system property that can be retrieved by System. getProperty(String) |
-jar | Runs a program contained in a JAR file whose manifest has a Main-Class entry. When this option is used, the class path is ignored. |
-verbos | Shows the classes that are loaded. This option may be useful to debug class loading problems. |
-Xmssize -Xmxsize | Sets the initial or maximum heap size. The size is a value in bytes. Add a suffix k or m for kilobytes or megabytes, for example, -Xmx10m |
SECTION 16 Common Java Options
Option | Description |
-cp or -classpath | Sets the class path, used to search for class fiels. See the previous tabl for defails. Not that javac can succeed when java fails if the current directory is on the source path but not the class path. |
-ea or - enableassertions | Enable assertions. By default, assertions are disabled |
- Dproperty=value | Sets a system property that can be retrieved by System.getProperty(String) |
-jar | Runs a program contained in a JAR file whose manifest has a Main-Class entry. When this option is used, the class path is ignored |
-verbose | Show the classes that are loaded. This option may ne useful to debug class loadding problems |
-Xmssize - Xmxsize | Set the initial or maximum heap size. The size is a value in bytes. Add a suffix k or m for kilobytes or megabytes, for example -Xms10m |
끝.... 번역 안한건.. 나중에
ㅎㅎㅎ
'Java' 카테고리의 다른 글
core java 따라하기 - 1 (0) | 2017.06.13 |
---|---|
JUnit5 개념 잡기 (0) | 2017.06.02 |
java8 StringJoiner 과 String.join 활용 (0) | 2016.01.05 |
ThreadLocal 이 뭘까요? (0) | 2016.01.05 |
Apache Daemon 에 대해서 (3) | 2015.12.08 |
Runtime.addShutdownHook() (0) | 2015.09.30 |
Top 10 Useful, Yet paranoid Java Programming Techniques (0) | 2015.09.15 |
Exception (0) | 2013.08.04 |
Regular Expressions in Java (0) | 2013.07.30 |
Delegate, Event , Ramda (0) | 2013.07.04 |