'자바' 카테고리의 다른 글
| 12회 한국 자바 개발자 컨퍼런스 (5) | 2012.01.26 |
|---|---|
| 객체를 Json 형태로 출력하기 (6) | 2010.05.23 |
| 제10회 한국자바개발자 컨퍼런스 (0) | 2009.02.05 |
| 12회 한국 자바 개발자 컨퍼런스 (5) | 2012.01.26 |
|---|---|
| 객체를 Json 형태로 출력하기 (6) | 2010.05.23 |
| 제10회 한국자바개발자 컨퍼런스 (0) | 2009.02.05 |
| 12회 한국 자바 개발자 컨퍼런스 (5) | 2012.01.26 |
|---|---|
| 객체를 Json 형태로 출력하기 (6) | 2010.05.23 |
| 제10회 한국자바개발자 컨퍼런스 (0) | 2009.02.05 |
| 코드 크게 |
자바의 정규표현식은 J2SE 1.4 부터 지원되지 시작했습니다. 관련된 주요 클래스들는 java.util.regex 팩키지에 있습니다.
Pattern 객체는 Perl 문법과 비슷한 형태로 정의된 정규표현식을 나타냅니다. 문자열로 정의한 정규표현식은 사용되기 전에 반드시 Pattern 클래스의 인스턴스로 컴파일되어야 합니다. 컴파일된 패턴은 Matcher 객체를 만드는 데 사용되며, Matcher 객체는 임의의 입력 문자열이 패턴에 부합되는 지 여부를 판가름하는 기능을 담당하합니다. 또한 Pattern 객체들은 비상태유지 객체들이기 때문에 여러 개의 Matcher 객체들이 공유할 수 있습니다.
Matcher 객체는 특정한 문자열이 주어진 패턴과 일치하는가를 알아보는데 이용됩니다. Matcher 클래스의 입력값으로는 CharSequence라는 새로운 인터페이스가 사용되는데 이를 통해 다양한 형태의 입력 데이터로부터 문자 단위의 매칭 기능을 지원 받을 수 있습니다. 기본적으로 제공되는 CharSequence 객체들은 CharBuffer, String, StringBuffer 클래스가 있습니다.
Matcher 객체는 Pattern 객체의 matcher 메소드를 통해 얻어진다. Matcher 객체가 일단 만들어지면 주로 세 가지 목적으로 사용됩다.
이들 메소드는 성공 시 true를 실패 시 false 를 반환합니다.
또한 특정 문자열을 찾아 새로운 문자열로 교체하는 기능도 제공됩니다. appendRepalcement 메소드는 일치하는 패턴이 나타날 때까지의 모든 문자들을 버퍼로 옮기고 찾아진 문자열 대신 교체 문자열로 채워 넣습니다. 또한 appendTail 메소드는 캐릭터 시퀀스의 현재 위치 이후의 문자들을 버퍼에 복사해 넣습니다. 다음 절에 나오는 예제 코드를 참고하도록 합시다.
CharSequence 인터페이스는 다양한 형태의 캐릭터 시퀀스에 대해 일관적인 접근 방법을 제공하기 위해 새로 생겨났으며, java.lang 패키지에 존재합니다. 기본적으로 String, StringBuffer, CharBuffer 클래스가 이를 구현하고 있으므로 적절한 것을 골라 사용하면 되며, 인터페이스가 간단하므로 필요하면 직접 이를 구현해 새로 하나 만들어도 됩니다.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 정규표현식 기본 사용 예제
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest01 {
public static void main(String[] args) {
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
if (b) {
System.out.println("match");
} else {
System.out.println("not match");
}
}
} |
match |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 문자열 치환 예제
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest02 {
public static void main(String[] args) {
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
// or
//String str = m.replaceAll("dog");
//System.out.println(str);
}
} |
one dog two dogs in the yard |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 이메일주소 유효검사
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest03 {
public static boolean isValidEmail(String email) {
Pattern p = Pattern.compile("^(?:\\w+\\.?)*\\w+@(?:\\w+\\.)+\\w+$");
Matcher m = p.matcher(email);
return m.matches();
}
public static void main(String[] args) {
String[] emails = { "test@abc.com", "a@.com", "abc@mydomain" };
for (int i = 0; i < emails.length; i ++) {
if (isValidEmail(emails[i])) {
System.out.println(emails[i]);
}
}
}
} |
test@abc.com |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* HTML 태그 제거
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest04 {
public static String stripHTML(String htmlStr) {
Pattern p = Pattern.compile("<(?:.|\\s)*?>");
Matcher m = p.matcher(htmlStr);
return m.replaceAll("");
}
public static void main(String[] args) {
String htmlStr = "<html><body><h1>Java2go.net</h1>"
+ " <p>Sehwan@Noh's Personal Workspace...</p></body></html>";
System.out.println(stripHTML(htmlStr));
}
} |
Java2go.net Sehwan@Noh's Personal Workspace... |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* HTML 링크 만들기
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest05 {
public static String linkedText(String sText) {
Pattern p = Pattern.compile("(http|https|ftp)://[^\\s^\\.]+(\\.[^\\s^\\.]+)*");
Matcher m = p.matcher(sText);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "<a href='" + m.group()+"'>" + m.group() + "</a>");
}
m.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) {
String strText = "My homepage URL is http://www.java2go.net/home/index.html.";
System.out.println(linkedText(strText));
}
}
|
My homepage URL is <a href='http://www.java2go.net/index.html'>http://www.java2go.net/index.html</a>. |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 금지어 필터링하기
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest06 {
public static String filterText(String sText) {
Pattern p = Pattern.compile("fuck|shit|개새끼", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(sText);
StringBuffer sb = new StringBuffer();
while (m.find()) {
//System.out.println(m.group());
m.appendReplacement(sb, maskWord(m.group()));
}
m.appendTail(sb);
//System.out.println(sb.toString());
return sb.toString();
}
public static String maskWord(String word) {
StringBuffer buff = new StringBuffer();
char[] ch = word.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (i < 1) {
buff.append(ch[i]);
} else {
buff.append("*");
}
}
return buff.toString();
}
public static void main(String[] args) {
String sText = "Shit! Read the fucking manual. 개새끼야.";
System.out.println(filterText(sText));
}
} |
S***! Read the f***ing manual. 개**야. |
A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.
A typical invocation sequence is thus
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();A matches method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement
boolean b = Pattern.matches("a*b", "aaaaab");is equivalent to the three statements above, though for repeated matches it is less efficient since it does not allow the compiled pattern to be reused.Instances of this class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.
| Construct | Matches |
|---|---|
| Characters | |
| x | The character x |
| \\ | The backslash character |
| \0n | The character with octal value 0n (0 <= n <= 7) |
| \0nn | The character with octal value 0nn (0 <= n <= 7) |
| \0mnn | The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7) |
| \xhh | The character with hexadecimal value 0xhh |
| \uhhhh | The character with hexadecimal value 0xhhhh |
| \t | The tab character ('\u0009') |
| \n | The newline (line feed) character ('\u000A') |
| \r | The carriage-return character ('\u000D') |
| \f | The form-feed character ('\u000C') |
| \a | The alert (bell) character ('\u0007') |
| \e | The escape character ('\u001B') |
| \cx | The control character corresponding to x |
| Character classes | |
| [abc] | a, b, or c (simple class) |
| [^abc] | Any character except a, b, or c (negation) |
| [a-zA-Z] | a through z or A through Z, inclusive (range) |
| [a-d[m-p]] | a through d, or m through p: [a-dm-p] (union) |
| [a-z&&[def]] | d, e, or f (intersection) |
| [a-z&&[^bc]] | a through z, except for b and c: [ad-z] (subtraction) |
| [a-z&&[^m-p]] | a through z, and not m through p: [a-lq-z](subtraction) |
| Predefined character classes | |
| . | Any character (may or may not match line terminators) |
| \d | A digit: [0-9] |
| \D | A non-digit: [^0-9] |
| \s | A whitespace character: [ \t\n\x0B\f\r] |
| \S | A non-whitespace character: [^\s] |
| \w | A word character: [a-zA-Z_0-9] |
| \W | A non-word character: [^\w] |
| POSIX character classes (US-ASCII only) | |
| \p{Lower} | A lower-case alphabetic character: [a-z] |
| \p{Upper} | An upper-case alphabetic character:[A-Z] |
| \p{ASCII} | All ASCII:[\x00-\x7F] |
| \p{Alpha} | An alphabetic character:[\p{Lower}\p{Upper}] |
| \p{Digit} | A decimal digit: [0-9] |
| \p{Alnum} | An alphanumeric character:[\p{Alpha}\p{Digit}] |
| \p{Punct} | Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ |
| \p{Graph} | A visible character: [\p{Alnum}\p{Punct}] |
| \p{Print} | A printable character: [\p{Graph}\x20] |
| \p{Blank} | A space or a tab: [ \t] |
| \p{Cntrl} | A control character: [\x00-\x1F\x7F] |
| \p{XDigit} | A hexadecimal digit: [0-9a-fA-F] |
| \p{Space} | A whitespace character: [ \t\n\x0B\f\r] |
| java.lang.Character classes (simple java character type) | |
| \p{javaLowerCase} | Equivalent to java.lang.Character.isLowerCase() |
| \p{javaUpperCase} | Equivalent to java.lang.Character.isUpperCase() |
| \p{javaWhitespace} | Equivalent to java.lang.Character.isWhitespace() |
| \p{javaMirrored} | Equivalent to java.lang.Character.isMirrored() |
| Classes for Unicode blocks and categories | |
| \p{InGreek} | A character in the Greek block (simple block) |
| \p{Lu} | An uppercase letter (simple category) |
| \p{Sc} | A currency symbol |
| \P{InGreek} | Any character except one in the Greek block (negation) |
| [\p{L}&&[^\p{Lu}]] | Any letter except an uppercase letter (subtraction) |
| Boundary matchers | |
| ^ | The beginning of a line |
| $ | The end of a line |
| \b | A word boundary |
| \B | A non-word boundary |
| \A | The beginning of the input |
| \G | The end of the previous match |
| \Z | The end of the input but for the final terminator, if any |
| \z | The end of the input |
| Greedy quantifiers | |
| X? | X, once or not at all |
| X* | X, zero or more times |
| X+ | X, one or more times |
| X{n} | X, exactly n times |
| X{n,} | X, at least n times |
| X{n,m} | X, at least n but not more than m times |
| Reluctant quantifiers | |
| X?? | X, once or not at all |
| X*? | X, zero or more times |
| X+? | X, one or more times |
| X{n}? | X, exactly n times |
| X{n,}? | X, at least n times |
| X{n,m}? | X, at least n but not more than m times |
| Possessive quantifiers | |
| X?+ | X, once or not at all |
| X*+ | X, zero or more times |
| X++ | X, one or more times |
| X{n}+ | X, exactly n times |
| X{n,}+ | X, at least n times |
| X{n,m}+ | X, at least n but not more than m times |
| Logical operators | |
| XY | X followed by Y |
| X|Y | Either X or Y |
| (X) | X, as a capturing group |
| Back references | |
| \n | Whatever the nth capturing group matched |
| Quotation | |
| \ | Nothing, but quotes the following character |
| \Q | Nothing, but quotes all characters until \E |
| \E | Nothing, but ends quoting started by \Q |
| Special constructs (non-capturing) | |
| (?:X) | X, as a non-capturing group |
| (?idmsux-idmsux) | Nothing, but turns match flags on - off |
| (?idmsux-idmsux:X) | X, as a non-capturing group with the given flags on - off |
| (?=X) | X, via zero-width positive lookahead |
| (?!X) | X, via zero-width negative lookahead |
| (?<=X) | X, via zero-width positive lookbehind |
| (?<!X) | X, via zero-width negative lookbehind |
| (?>X) | X, as an independent, non-capturing group |
The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.
It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
Backslashes within string literals in Java source code are interpreted as required by the Java Language Specification as either Unicode escapes or other character escapes. It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.
Character classes may appear within other character classes, and may be composed by the union operator (implicit) and the intersection operator (&&). The union operator denotes a class that contains every character that is in at least one of its operand classes. The intersection operator denotes a class that contains every character that is in both of its operand classes.
The precedence of character-class operators is as follows, from highest to lowest:
1 Literal escape \x 2 Grouping [...] 3 Range a-z 4 Union [a-e][i-u] 5 Intersection [a-z&&[aeiou]]
Note that a different set of metacharacters are in effect inside a character class than outside a character class. For instance, the regular expression . loses its special meaning inside a character class, while the expression - becomes a range forming metacharacter.
A line terminator is a one- or two-character sequence that marks the end of a line of the input character sequence. The following are recognized as line terminators:
If UNIX_LINES mode is activated, then the only line terminators recognized are newline characters.
The regular expression . matches any character except a line terminator unless the DOTALL flag is specified.
By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input. When in MULTILINE mode $ matches just before a line terminator or the end of the input sequence.
Capturing groups are numbered by counting their opening parentheses from left to right. In the expression ((A)(B(C))), for example, there are four such groups:
1 ((A)(B(C))) 2 (A) 3 (B(C)) 4 (C)
Group zero always stands for the entire expression.
Capturing groups are so named because, during a match, each subsequence of the input sequence that matches such a group is saved. The captured subsequence may be used later in the expression, via a back reference, and may also be retrieved from the matcher once the match operation is complete.
The captured input associated with a group is always the subsequence that the group most recently matched. If a group is evaluated a second time because of quantification then its previously-captured value, if any, will be retained if the second evaluation fails. Matching the string "aba" against the expression (a(b)?)+, for example, leaves group two set to "b". All captured input is discarded at the beginning of each match.
Groups beginning with (? are pure, non-capturing groups that do not capture text and do not count towards the group total.
This class is in conformance with Level 1 of Unicode Technical Standard #18: Unicode Regular Expression Guidelines, plus RL2.1 Canonical Equivalents.
Unicode escape sequences such as \u2014 in Java source code are processed as described in ?.3 of the Java Language Specification. Such escape sequences are also implemented directly by the regular-expression parser so that Unicode escapes can be used in expressions that are read from files or from the keyboard. Thus the strings "\u2014" and "\\u2014", while not equal, compile into the same pattern, which matches the character with hexadecimal value 0x2014.
Unicode blocks and categories are written with the \p and \P constructs as in Perl. \p{prop} matches if the input has the property prop, while \P{prop} does not match if the input has that property. Blocks are specified with the prefix In, as in InMongolian. Categories may be specified with the optional prefix Is: Both \p{L} and \p{IsL} denote the category of Unicode letters. Blocks and categories can be used both inside and outside of a character class.
The supported categories are those of The Unicode Standard in the version specified by the Character class. The category names are those defined in the Standard, both normative and informative. The block names supported by Pattern are the valid block names accepted and defined by UnicodeBlock.forName.
Categories that behave like the java.lang.Character boolean ismethodname methods (except for the deprecated ones) are available through the same \p{prop} syntax where the specified property has the name javamethodname.
The Pattern engine performs traditional NFA-based matching with ordered alternation as occurs in Perl 5.
Perl constructs not supported by this class:
The conditional constructs (?{X}) and (?(condition)X|Y),
The embedded code constructs (?{code}) and (??{code}),
The embedded comment syntax (?#comment), and
The preprocessing operations \l \u, \L, and \U.
Constructs supported by this class but not by Perl:
Possessive quantifiers, which greedily match as much as they can and do not back off, even when doing so would allow the overall match to succeed.
Character-class union and intersection as described above.
Notable differences from Perl:
In Perl, \1 through \9 are always interpreted as back references; a backslash-escaped number greater than 9 is treated as a back reference if at least that many subexpressions exist, otherwise it is interpreted, if possible, as an octal escape. In this class octal escapes must always begin with a zero. In this class, \1 through \9 are always interpreted as back references, and a larger number is accepted as a back reference if at least that many subexpressions exist at that point in the regular expression, otherwise the parser will drop digits until the number is smaller or equal to the existing number of groups or it is one digit.
Perl uses the g flag to request a match that resumes where the last match left off. This functionality is provided implicitly by the Matcher class: Repeated invocations of the find method will resume where the last match left off, unless the matcher is reset.
In Perl, embedded flags at the top level of an expression affect the whole expression. In this class, embedded flags always take effect at the point at which they appear, whether they are at the top level or within a group; in the latter case, flags are restored at the end of the group just as in Perl.
Perl is forgiving about malformed matching constructs, as in the expression *a, as well as dangling brackets, as in the expression abc], and treats them as literals. This class also accepts dangling brackets but is strict about dangling metacharacters like +, ? and *, and will throw a PatternSyntaxException if it encounters them.
마지막 수정일: 2006년 8월 23일
| 정규식을 이용한 다양한 예제 (3) | 2010.05.16 |
|---|---|
| CallableStatement 사용하기 (0) | 2008.06.26 |
| Oracle의 Stored Procedure, Function 이용하기 (0) | 2008.06.26 |
| 소수점 연산 (0) | 2008.06.26 |
| Jakarta POI Excel File 읽기, 쓰기, 셀컨트롤, 이미지 삽입 (1) | 2008.06.26 |
Un policier afghan a été tué mardi à Kaboul dans l'explosion d'un obus qu'il tentait de désamorcer, http://www.moncleroutletespain.com/ moncler chaquetas, a indiqué un responsable de la police, http://www.moncleroutletespain.com/ moncler online, ajoutant ne pas savoir si la munition datait de précédents conflits en Afghanistan ou avait été placée là à dessein comme bombe artisanale, http://www.moncleroutletespain.com/ moncler outlet.Related articles:
http://reviewforum.pe.kr/3439 http://reviewforum.pe.kr/3439
http://www.yeory.com/59 http://www.yeory.com/59
기고한지 한달이 지나서 SDN에 올라와서 1.0 정식 버전이 발표된 후에야 이 글을 오픈한당. ㅡ_ㅡ;;
암튼 고고고~~~
필자는 작년부터 Web 2.0과 함께 부상한 RIA(Rich Internet Application)에 대해 귀가 따갑게 들어왔다. 필자가 현재 몸담고 있는 JCO내에서도 JCO가 직간접적으로 관여하는 각종 세미나 및 행사에서도 RIA는 큰 화두였으며 지금까지도 관심을 끄는 이슈로 부각되고 있다. 이런 이슈에 호응(?)하기 위해 Sun, Adobe, MS에서 JavaFX, Flex, Silverlight 라는 삼총사를 내놓았다. 세가지를 비교하는 것도 재미있는 일이겠지만 본인은 자바 프로그래머로만 10년 가까이 먹고 살았다. Silverlight는 어떤 것 이라는 것만 아는 편이고 Flex는 약간 끄적거려 보았다. 결국 가장 자신있는 Java 진영에서 나온 JavaFX 를 다루어 보기로 했다.
JavaFX를 처음 접한 것은 2007 JavaOne 이 끝난 후였다. 국내 유일의 자바 챔피언인 양수열 고문이(참고로 본인의 친형이다) JavaOne이 끝나고 귀국하고 만난 자리에서 JavaFX가 앞으로 엄청난 발전을 할 것이라고 흥분해서 말했던 기억이 있다. 그 후 몇 가지 관련된 글을 보았었고 2008년 JavaOne에 운이 좋게 참석하게 되어 다시 보게 된 JavaFX는 정말 놀라울 정도로 발전해 있었다. 예전에 간단한 Flash ActionScript 같았던 모습에서 Multimedia 쪽이 대폭 강화되어 수많은 동영상이 화면에 Display되면서 자유롭게 떠도는 Demo를 보고 그 놀라운 Performance에 놀라움을 금치 못했다. 그러면서도 ‘저 Demo가 일반적인 PC에서도 저만큼 가능할까?’ 라는 의문이 들었다. 그래서 결국 만들어 보게 되었으니…
시작하기
JavaFX를 처음 접하면서 느낀점은 JavaFX 문법이 JavaScript와 상당히 닮아 있다는 점이었다. JavaScript와 Java의 절묘한 짬뽕(?)이랄까? JavaFX Application을 물론 메모장으로도 개발할 수 있지만 IDE에 길들여진 개발자들이 메모장으로 개발할리가 없다. 그리고 JavaFX를 전면에 내세운 Sun에서도 개발자들이 편하고 능률적으로 개발할 수 있도록 NetBeans 최신버전에 JavaFX plugin을 추가해 놓았다. 이전에는 JavaFX Pad라는 응용 프로그램을 활용했었으나 좀 더 융통성있고 편하게 개발할 수 있도록 NetBeans에 통합해 놓은 것이다. JavaFX Pad에서와 같이 Source Edit 창에서 코드를 변경하면 위쪽 Preview 영역에서 바로 변경된 결과물을 볼 수 있고 오른쪽 팔레트를 이용해 각종 콤포넌트나 노드 이벤트 등을 원클릭으로 소스에 적용할 수 있다.
NetBeans JavaFX plugin 설치는 신상철 박사님이 운영하시는 JavaPassion을 참고하면 편하게 설정할 수 있다. (http://www.javapassion.com/handsonlabs/javafx_basics1/)

[JavaFX plugin을 설치하고 실행중인 모습]
본론으로
JavaFX를 이용해 Multimedia 파일을 컨트롤 하기 위해 필요한 정보와 샘플들을 우선 수집하였다. 일차적으로 Sample Code를 몇 개 받아 mp3 파일을 재생하는 테스트 코드를 만들었을 때 mp3 파일은 아주 잘 재생되었다. 하지만 동영상 파일로 바꾸었을 때는 아래와 같은 에러를 발생시켰다.
|
FX Media Object caught Exception com.sun.media.jmc.MediaUnsupportedException: Unsupported media: file:/D:/Projects/NetBeans/SimpleMovie/build/classes/simplemovie/SoHot.avi source ='file:/D:/Projects/NetBeans/SimpleMovie/build/classes/simplemovie/SoHot.avi' |
Exception의 이름으로 인해 해당 동영상 파일이 FX 에서 지원하지 않는 Media 형식인걸 확인하였고 빠르게 손가락은 구글링을 하여 JavaFX가 지원하는 미디어 포멧을 찾아내었다.
|
JavaFX Media 지원타입 |
|
Container
Types: ASF
(Advanced Systems Format),MPEG-1, AVI (Audio-Video Interleaved),WAVE, MIDI
(Standard MIDI) Encoding
Types: WMAUDIO8
(WindowsMedia Audio 2/7/8),WMSCREEN (Windows Media Screen), WMVIDEO9 (Windows
Media Video 9), Voxware, MS MPEG-4, WMVIDEO7 (Windows Media Video 7), MPEG11
Video, MPEG-1 Audio, Uncompressed video (RGB/YUV/RLE), PCM, ADPCM, MP3, MIDI Protocol
Types: HTTP, FILE Known not to work at present are media with
DRM (Digital Rights Management), and media played directly from DVD or CD. |
Multimedia 파일을 컨트롤 하기 위해서는 항상 Codec이 문제인데 JavaFX에서는 생각보다 많은 종류의 Codec을 지원해주어 특별히 Codec에 신경 쓰지 않아도 되었다. (물론 가지고 있는 많은 수의 동영상은 실행되지 않았다.)
몇 가지 문제를 잡아나가면서 만들어 낸 결과물은 CustomNode를 사용해 재사용할 수 있는MediaViewNode를 만들었고 Timeline을 이용해 이 Node에 Animation 효과를 보여주는 프로그램을 만들어 보았다. 아래 소스를 실행하면 0.2 배율 스케일의 동영상 화면이 정지된 채로 실행되고 클릭시 회전하며 원래 비율로 커지고 실행되는 프로그램이다.
Source
|
/* * Main.fx * * Created on 2008. 11. 8, 오후 1:29:49 */ package simplemovie; import javafx.ext.swing.*; import javafx.scene.*; import javafx.scene.media.*; import javafx.scene.effect.*; import javafx.scene.paint.Color; /** * @author eclips */ SwingFrame { title: "Movie Player" width: 800 height: 600 closeAction: function() { java.lang.System.exit( 0 ); } visible: true menus: [ ] content: Canvas { width:800 height:600 background: Color.WHITE content: [ MediaViewNode { // {__DIR__}은 클래스 파일이 있는 디렉토리이다 mediaURL: "{__DIR__}Nobody.avi" viewX: 10 viewY: 10 } ] } } |
|
|
/* * MediaViewNode.fx * * Created on 2008. 11. 8, 오후 6:48:47 */ package simplemovie; /** * @author eclips */ import java.lang.System; import javafx.scene.CustomNode; import javafx.scene.*; import javafx.input.*; import javafx.scene.media.*; import javafx.scene.effect.*; import javafx.scene.paint.Color; import javafx.scene.geometry.*; import javafx.scene.transform.*; import javafx.animation.Timeline; import javafx.animation.KeyFrame; import javafx.animation.Interpolator; public class MediaViewNode extends CustomNode { /** * 동영상 화면의 X Sacle */ public attribute viewScaleX:Number = 0.2;
/** * 동영상 화면의 Y Scale */ public attribute viewScaleY:Number = 0.2;
/** * MediaViewNode의 회전 반경 */ public attribute rotation:Number = 0.0;
public attribute viewX:Number = 50; public attribute viewY:Number = 40;
/** * 현재 활성화 여부 */ private attribute actived:Boolean = false; /** * 현재 Animation 중인지 여부 */ private attribute moving:Boolean = false;
private attribute media:Media; private attribute mediaView:MediaView;
private attribute strokeColor:Color = Color.DARKGRAY;
// 동영상 미디어 객체 URL public attribute mediaURL:String on replace { media = Media { source: mediaURL }; }
// Media Player 객체 private attribute player = MediaPlayer { media: media, autoPlay: false }
private attribute choiceTimeLine = Timeline { keyFrames : [ KeyFrame { time: 0ms values: [ viewScaleX => 0.2, viewScaleY => 0.2, viewX => 10, viewY => 10, rotation => 0.0, moving => true ] }, KeyFrame { time : 500ms values: [ viewScaleX => 1.0 tween Interpolator.LINEAR, viewScaleY => 1.0 tween Interpolator.LINEAR, viewX => 40 tween Interpolator.LINEAR, viewY => 40 tween Interpolator.LINEAR, rotation => 360 tween Interpolator.LINEAR, moving => false ] action: function():Void { player.play(); mediaView.toFront(); actived = true; } } ] };
private attribute unchoiceTimeLine = Timeline { keyFrames : [ KeyFrame { time: 0ms values: [ viewScaleX => 1.0, viewScaleY => 1.0, viewX => 40, viewY => 40, rotation => 360, moving => true ] }, KeyFrame { time : 500ms values: [ viewScaleX => 0.2 tween Interpolator.LINEAR, viewScaleY => 0.2 tween Interpolator.LINEAR, viewX => 10 tween Interpolator.LINEAR, viewY => 10 tween Interpolator.LINEAR, rotation => 0.0 tween Interpolator.LINEAR, moving => false ] action: function():Void { player.pause(); mediaView.toBack(); actived = false; } } ] };
public function create():Node { Group { content: [ this.mediaView = MediaView { mediaPlayer: player scaleX: bind viewScaleX scaleY: bind viewScaleY translateX: bind viewX translateY: bind viewY transform: bind [Transform.rotate(rotation,200,150)] onMouseEntered: function(me:MouseEvent):Void { strokeColor = Color.BLACK } onMouseExited: function(me:MouseEvent):Void { strokeColor = Color.DARKGRAY } onMouseClicked: function(me:MouseEvent):Void { System.out.println("clicked => " + actived); if(moving == false) { if(actived) { unchoiceTimeLine.start(); System.out.println("inactive - " + viewScaleX); } else { choiceTimeLine.start(); System.out.println("active - " + viewScaleX); } } } }, Rectangle { width: 708 height: 472 scaleX: bind viewScaleX scaleY: bind viewScaleY translateX: bind viewX translateY: bind viewY stroke: strokeColor strokeWidth: 10 transform: bind [Transform.rotate(rotation,200,150)] onMouseEntered: function(me:MouseEvent):Void { strokeColor = Color.BLACK } onMouseExited: function(me:MouseEvent):Void { strokeColor = Color.DARKGRAY } } ] } } } |
|
실행 결과
Clip을 클릭하면 해당 동영상 클립이 회전하면서 1:1 스케일로 커지면서 동영상이 실행된다.
아쉬운 것들
l JavaFX Document의 부실함
n 작업을 위해 다운 받아 펼쳐본 Document는 한마디로 부실함이었다. 물론 아직 초기 버전이라 그런 것이라 생각되지만 현재의 Document는 그냥 어떤 것이 있다는 것을 설명하기 위해 만들어 놓은 수준이라고 봐야 할 것 같다. JDK SE 버전의 Document에 비하면 정말 완성도가 떨어졌다.
l NetBeans JavaFX plugin
n 미디어 이름에 한글이 들어가거나 공백이 있을 경우 실행시 에러가 발생한다.
n 실시간으로 코딩시 에러 내용이 표시되는데 간혹 이런 에러 내용이 잘못 표시되는 문제
n 미디어의 이름을 바꿀 경우 간혹 미디어 적용이 안되 Rebuild 해야하는 불편함
n 소스에서 사용되는 클래스에 대해 자동으로 import 되지 않는 불편함
이런 문제들은 앞으로 JavaFX 1.0 정식 버전이 나오고 plugin이 업그레이드 되면서 점점 좋아질 것이라고 생각하지만 아직까지는 약간의 불편함을 감수하고 개발해야 한다.
JavaFX로 간단한 동영상 실행 Application을 만들면서 어떻게 이렇게 간단할 수 있지? 하는 생각이 들었다. 이해하기 쉬운 코드 몇 줄로 꽤 대단한 애니메이션 효과를 줄 수 있었고 동영상 플레이도 코드 몇 줄로 끝났다. 자바 Application으로 만들려 했으면 엄청난 소스 코드 속에서 헤메야 간신히 나올만한 프로그램을 JavaFX의 스크립트 몇 줄이 해낸것이다. 물론 이런 힘이 JavaFX 에만 있는 것이 아니다. JavaFX가 경쟁하고 있는 Flex나 Silverlight도 비슷한 수준으로 지원하고 있거나 더 월등히 앞선 기능과 툴을 지원하고 있기도 하다. 지금 현재도 간단한 Application은 만들기 너무 쉽지만 정식 버전이 나올 시점이 되면 지금보다 모든 면에서 더욱 편하고 강력해져야 할 거라고 생각한다. 위쪽에서 지적한대로 Document도 현재 JDK 만큼 완성도가 높아져야 하며 IDE의 발전과 JavaFX가 적용될 수 있는 Platform도 더욱 넓어진다면 다양한 분야에서 JavaFX 가 활약하는 것을 볼 수 있을거라 생각한다.
참조사이트
http://www.javapassion.com/javafx/
http://java.sun.com/javafx/index.jsp
| 홈페이지를 구축을 위한 프로그램들을 개발 해보자 (0) | 2009.06.24 |
|---|---|
| Web Project 에서 View에서 사용하는 파일에 대한 경로 설정 기준 (0) | 2009.06.02 |
| [SDN 기고] JavaFX 와 Multimedia (0) | 2008.12.15 |
| 드디어 JavaFX 1.0 정식 Release... (0) | 2008.12.09 |
| Eclipse Ganymede 출동~ (0) | 2008.07.02 |
| JSON (0) | 2008.06.26 |
출처 : http://link.allblog.net/11939288
| [SDN 기고] JavaFX 와 Multimedia (0) | 2008.12.15 |
|---|---|
| 드디어 JavaFX 1.0 정식 Release... (0) | 2008.12.09 |
| Eclipse Ganymede 출동~ (0) | 2008.07.02 |
| JSON (0) | 2008.06.26 |
| JSON vs XML (0) | 2008.06.26 |
| XML과 JSON 사이에 변환 패턴 (0) | 2008.06.26 |
클래스이름 = function(파라미터) {
this.id = 파라미터;
this.name = 파라미터;
}
Member = function( id, name ) {
this.id = id;
this.name = name;
}
var mem = new Member( 'testId', '창마이')
클래스이름.prototype.함수이름 = function( newId, newName ) {
this.id = newId;
this.name = newName;
}
Member.prototype.toString = function() {
return this.id + "[" + this.name + "]";
}
이방법 이외에 Object() 를 이용한 방법으로
var mem = new Object();
mem.id = 'testId';
mem.name = '창마이';
mem.securityNo = '7700001000000';
mem.toString = function() {
return this.name + "[" + this.id + "]";
}
alert( mem.toString() );
JSON 표기법
{ 이름1: 값1, 이름2: 값2, 이름3: 값3 }
var countries = {ko: '대한민국', fr: '프랑스', uk: '영국'};
var koName = countries.ko;
var frName = countries['fr'];
배열형식
[값0, 값1, 값2, 값3]
var countryCodes = ['ko', 'fr', 'uk', 'us'];
var idx0 = countryCodes[0]; //'ko'
var idx1 = countryCodes[2]; //'uk'
배열과 응용
var member = {
name: '창마이',
favorateColors: ['파랑', '노랑', '빨강']
};
var message = member.name + "님이 좋아하는 색상은 " +
member.favorateColors.length + "개이고,";
message += "그중 첫 번째 색상은 " +
member.favorateColors[0] + "입니다.";
JSON 표기법을 사용한 클래스 정의
클래스이름 = function( 파라미터 ) {
...
}
클래스이름.prototype = {
함수명1: function( 파라미터 ) {
....
},
함수명1: function( 파라미터 ) {
....
}
}
Ex)
Member = function(name, id, securityNo) {
this.name = name;
this.id = id;
this.securityNo = securityNo;
}
Member.prototype = {
setValue: function(newName, newId, newSecurityNo) {
this.name = newName;
this.id = newId;
this.securityNo = newSecurityNo;
},
getAge: function() {
var birthYear = parseInt(this.securityNo.substring(0, 2));
var code = this.securityNo.substring(6,7);
if (code == '1' || code == '2') {
birthYear += 1900;
} else if (code == '3' || code == '4') {
birthYear += 2000;
}
var today = new Date();
return today.getFullYear() - birthYear;
},
toString: function() {
return this.name + "[" + this.id + "]";
}
}
자바스크립트에서 패키지 정의하기
var ajax = new Object();
ajax.Request = function() {
...
}
ajax.Request.prototype = {
someFunction = function() {
...
},
...
}
위에 정의한 클래스 사용하기
var req = new ajax.Request();
req.someFunction();
중첩해서 패키지 만들기
var ajax = new Object();
ajax.xhr = new Object();
ajax.xhr.Request = function() {
...
}
// 아래와 같이 사용
var req = new ajax.xhr.Request();
빈 클래스 만들기
var ajax = {};
ajax.xhr = {};
ajax.xhr.Request = function() {
...
}
JSON 표기법에 대한 정보는 http://www.json.org/ 사이트에서 참고할 수 있다.
| JSON (0) | 2008.06.26 |
|---|---|
| JSON vs XML (0) | 2008.06.26 |
| XML과 JSON 사이에 변환 패턴 (0) | 2008.06.26 |
| JavaScript 객체 JSON (0) | 2008.06.26 |
| Java 객체를 이용해서 JSON객체를 위한 텍스트 생성하기 (0) | 2008.06.26 |
| Tomcat 5.X 버전에서 한글 파라메터 쓰기 (0) | 2008.06.26 |
http://blog.naver.com/eclips32/30020578345
Simple Java toolkit for JSON (JSON.simple)
==========================================
http://www.JSON.org/java/json_simple.zip
1.Why the Simple Java toolkit (also named as JSON.simple) for JSON?
When I use JSON as the data exchange format between the AJAX client and JSP
for the first time, what worry me mostly is how to encode Java strings and
numbers correctly in the server side so the AJAX client will receive a well
formed JSON data. When I looked into the 'JSON in Java' directory in JSON
website,I found that wrappers to JSONObject and JSONArray can be simpler,
due to the simplicity of JSON itself. So I wrote the JSON.simple package.
2.Is it simple,really?
I think so. Take an example:
import org.json.simple.JSONObject;
JSONObject obj=new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
System.out.print(obj);
Result:
{"nickname":null,"num":100,"balance":1000.21,"is_vip":true,"name":"foo"}
The JSONObject.toString() will escape controls and specials correctly.
3.How to use JSON.simple in JSP?
Take an example in JSP:
<%@page contentType="text/html; charset=UTF-8"%>
<%@page import="org.json.simple.JSONObject"%>
<%
JSONObject obj=new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
out.print(obj);
out.flush();
%>
So the AJAX client will get the responseText.
4.Some details about JSONObject?
JSONObject inherits java.util.HashMap,so it don't have to worry about the
mapping things between keys and values. Feel free to use the Map methods
like get(), put(), and remove() and others. JSONObject.toString() will
combine key value pairs to get the JSON data string. Values will be escaped
into JSON quote string format if it's an instance of java.lang.String. Other
type of instance like java.lang.Number,java.lang.Boolean,null,JSONObject and
JSONArray will NOT escape, just take their java.lang.String.valueOf() result.
null value will be the JSON 'null' in the result.
It's still correct if you put an instance of JSONObject or JSONArray into an
instance of JSONObject or JSONArray. Take the example about:
JSONObject obj2=new JSONObject();
obj2.put("phone","123456");
obj2.put("zip","7890");
obj.put("contact",obj2);
System.out.print(obj);
Result:
{"nickname":null,"num":100,"contact":{"phone":"123456","zip":"7890"},"balance":1000.21,"is_vip":true,"name":"foo"}
The method JSONObject.escape() is used to escape Java string into JSON quote
string. Controls and specials will be escaped correctly into \b,\f,\r,\n,\t,
\",\\,\/,\uhhhh.
5.Some detail about JSONArray?
org.json.simple.JSONArray inherits java.util.ArrayList. Feel free to use the
List methods like get(),add(),remove(),iterator() and so on. The rules of
JSONArray.toString() is similar to JSONObject.toString(). Here's the example:
import org.json.simple.JSONArray;
JSONArray array=new JSONArray();
array.add("hello");
array.add(new Integer(123));
array.add(new Boolean(false));
array.add(null);
array.add(new Double(123.45));
array.add(obj2);//see above
System.out.print(array);
Result:
["hello",123,false,null,123.45,{"phone":"123456","zip":"7890"}]
6.What is JSONValue for?
org.json.simple.JSONValue is use to parse JSON data into Java Object.
In JSON, the topmost entity is JSON value, not the JSON object. But
it's not necessary to wrap JSON string,boolean,number and null again,
for the Java has already had the according classes: java.lang.String,
java.lang.Boolean,java.lang.Number and null. The mapping is:
JSON Java
------------------------------------------------
string <=> java.lang.String
number <=> java.lang.Number
true|false <=> java.lang.Boolean
null <=> null
array <=> org.json.simple.JSONArray
object <=> org.json.simple.JSONObject
------------------------------------------------
JSONValue has only one kind of method, JSONValue.parse(), which receives
a java.io.Reader or java.lang.String. Return type of JSONValue.parse()
is according to the mapping above. If the input is incorrect in syntax or
there's exceptions during the parsing, I choose to return null, ignoring
the exception: I have no idea if it's a serious implementaion, but I think
it's convenient to the user.
Here's the example:
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
Object obj=JSONValue.parse(s);
JSONArray array=(JSONArray)obj;
System.out.println(array.get(1));
JSONObject obj2=(JSONObject)array.get(1);
System.out.println(obj2.get("1"));
Result:
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}
{"2":{"3":{"4":[5,{"6":7}]}}}
7.About the author.
I'm a Java EE developer on Linux.
I'm working on web systems and information retrieval systems.
I also develop 3D games and Flash games.
You can contact me through:
Fang Yidong<fangyidong@yahoo.com.cn>
Fang Yidong<fangyidng@gmail.com>
http://www.JSON.org/java/json_simple.zip
| JSON (0) | 2008.06.26 |
|---|---|
| JSON vs XML (0) | 2008.06.26 |
| XML과 JSON 사이에 변환 패턴 (0) | 2008.06.26 |
| JavaScript 객체 JSON (0) | 2008.06.26 |
| Java 객체를 이용해서 JSON객체를 위한 텍스트 생성하기 (0) | 2008.06.26 |
| Tomcat 5.X 버전에서 한글 파라메터 쓰기 (0) | 2008.06.26 |
Jakarta POI
I. POI 란?
일반적으로 POI가 엑셀파일을 쓰는 컴퍼넌트로 알려져 있으나 POI는 프로젝트 이름입니다.
즉 POI는 Microsoft Format File을 액세스 할 수 있는 API를 제공합니다. (한마디로 자바에서 MS파일을 읽고 쓸수있도록 지원합니다.)
POI안에는 여러 컴퍼넌트들이 있습니다.
① POIFS
Microsoft의 OLE2 포맷 형식의 문서를 자바로 읽고 쓸수 있는 컴퍼넌트입니다
기본적으로 POI의 모든 컴퍼넌트들이 POIFS를 사용합니다.
② HSSF
Microsoft의 엑셀파일을 읽고 쓸수 있도록 지원하는 컴퍼넌트입니다.
③ HWPF
Microsoft의 워드파일을 읽고 쓸수 있도록 지원하는 컴퍼넌트입니다.
이 컴퍼넌트는 디자인 초기단계입니다.
④ HPSF
Microsoft의 OLE2 포맷 형식의 문서 속성을 어플리케이션에서 사용 할수 있도록 지원하는 컴퍼넌트입니다.
현재 읽기 기능만 제공합니다
워드파일을 핸들링 하는 HWPF는 초기단계라 사용을 못하지만 기대는 되는군요 ^^
ps. 영어사전을 찾아보니 poi는 하와이의 토란 요리를 뜻하더군요.
우리나라말로 하니 자카르타 토란 프로젝트 쯤 될라나? ㅎㅎ
II. 다운로드 및 설치
다운로드 받으러 갑시다~!
http://jakarta.apache.org/site/downloads/downloads_poi.cgi
현재 2.5.1버젼입니다.
다운받은 파일을 압축을 풀면 *.jar 파일들이 있을겁니다 이 파일들을 자신의 어플리케이션 /lib/에 복사합시다
POI API http://jakarta.apache.org/poi/apidocs/index.html
Quick Guide http://jakarta.apache.org/poi/hssf/quick-guide.html
III. Formula(수식) 지원에 관해..
엑셀을 읽고 쓸때 수식을 지원합니다.
org.apache.poi.hssf.usermodel.HSSFCell의
setCellFormula("formulaString") 메쏘드는 스프레드시트에 수식을 추가하는데 사용되며
getCellFormula() 메쏘드는 수식을 대표하는 문자열을 해석하는데 사용됩니다. 하지만 엑셀에서 사용하는 수식을 모두
사용 할 수는 없습니다.
① 지원되는 부분
-. 셀 참조, 시트참조, 지역참조
-. 상대적 혹은 절대적 참조
-. 수연산 및 논리연산
-. 시트 혹은 매크로 함수
-. 수식 결과값 반환
② 부분적 지원
문자열을 포함하는 수식을 해석할 수는 있지만 문자열값을 반환하는 수식은 아직 지원하지 않습니다.
③ 지원되지 않는 부분
-. 배열 수식
-. 1진법 수식
-. 3D 참조
-. 에러 값 (cells containing #REF's or #VALUE's)
IV. 기본객체
가장 기본이되는 객체가 다음 4가지 입니다
이름에서 무엇을 뜻하는지 대강 짐작 할 수 있겠죵?
① HSSFWorkbook - 엑셀 워크북을 말합니다.
② HSSFSheet - 엑셀 쉬트를 나타냅니다.
③ HSSFRow - 엑셀에서 특정 행입니다.
④ HSSFCell - 엑셀에서 특정 행에대한 특정 셀입니다
위 4가지 객체는 앞으로 계속 나올겁니다. 눈여겨 미리 봐 둡시다. @.@
V. 엑셀 읽기 예제
① POSFS을 이용하여 엑셀 워크북을 생성합니다.
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("excelfile.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(fs);
② 생성된 워크북을 이용하여 시트 수만큼 돌면서 엑셀 시트 하나씩을 생성합니다.
int sheetNum = workbook.getNumberOfSheets();
for (int k = 0; k < sheetNum; k++) {
System.out.println("Sheet Number : "+k);
System.out.println(Sheet Name : " + workbook.getSheetName(k));
HSSFSheet sheet = workbook.getSheetAt(k);
}
③ 생성된 시트를 이용하여 그 행의 수만큼 돌면서 행을 하나씩 생성합니다.
int rows = sheet.getPhysicalNumberOfRows();
for (int r = 0; r < rows; r++) {
HSSFRow row = sheet.getRow(r);
System.out.println("Row : "+row.getRowNum());
}
④ 역시나 생성된 행을 이용하여 그 셀의 수만큼 돌면서 셀을 하나씩 생성합니다.
int cells = row.getPhysicalNumberOfCells();
for (short c = 0; c < cells; c++) { <--!! short 형입니다. 255개가 max!int celltype = cell.getCellType();
...
}
셀을 생성하여 셀 타입에 따라 처리를 해주면 끝~
⑤ 주의사항
만약 엑셀에서 A열에 아무런 값이 없으면 그 행은 읽지 못합니다.
행을 읽지 못하니 셀또한 처리 할 수 없습니다
VI. 엑셀읽기 샘플소스
샘플 데이터
A열은 B열에 대한 셀 타입을 나타내며 C열은 D열에대한 셀 타입을 나타냅니다.
즉 B:1 의 123456의 셀 타입은 A:1 일반 이라는 것이며 마찬가지로
D:1의 2005-02-09의 셀타입은 C:1 사용자정의로 세팅하였다는 겁니다
이 엑셀의 데이터를 다음 소스로 읽어 보겠습니다.
|
<%@ page <html> <% String excelfile = "C:\\Tomcat 5.0\\webapps\\ROOT\\example.xls"; try { //워크북을 생성! HSSFWorkbook workbook = new HSSFWorkbook(fs); int sheetNum = workbook.getNumberOfSheets(); for (int k = 0; k < sheetNum; k++) { //시트 이름과 시트번호를 추출 <br><br> for (int r = 0; r < rows; r++) { // 시트에 대한 행을 하나씩 추출 for (short c = 0; c < cells; c++) { // 행에대한 셀을 하나씩 추출하여 셀 타입에 따라 처리 switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_FORMULA : %>
|
위 소스의 결과입니다.
|
Sheet Number 0 |
결과를 보니 사용자가 지정한 셀 타입에 관계없이
숫자관련 셀은 POI에서 모두 숫자 타입으로 인식해 버렸습니다.
날짜 역시 지정한 셀 타입에 관계없이 모두 숫자 타입으로 인식해 버리는군요!
그럼 어떻게 날짜를 제대로 표현할까요?
날짜 타입을 제대로 나타내기 위해서는 날짜 Cell에는 getDateCellValue()를 사용하면
정상적으로 처리 할 수 있습니다.
SimpleDateformat sdf = new SimpleDateformat("yyyy-MM-dd hh:mm");
String date = sdf.format(cell.getDateCellValue());
등을 이용하면 나타내고자 하는 알짜를 표현 하기 더 쉽겠지요
나머지 수식을 가져 올때도 마찬가지입니다. 이런 사항을 도표로 나타내보았습니다.
org.apache.poi.hssf.usermodel.HSSFCell 에는 모두 6가지의 Cell Type이 있는데,
cell.getCellType()을 하면 그 셀의 반환값을 알 수 있으며 그에 상응하는 static 필드타입은 다음과 같습니다.
| 셀타입 | 필드타입 |
함수 |
함수반환값 |
| 0 | CELL_TYPE_NUMERIC |
getNumericCellValue() -> 숫자 타입일때 getDateCellValue() -> 날짜 타입일때 |
double Date |
| 1 | CELL_TYPE_STRING |
getStringCellValue() |
String |
| 2 | CELL_TYPE_FORMULA |
getCellFormula() -> 수식자체를 가져올때 getNumericCellValue() -> 수식 반환값이 숫자일때 getStringCellValue() -> 수식 반환값이 문자일때 |
String double String |
| 3 | CELL_TYPE_BLANK |
|
|
| 4 | CELL_TYPE_BOOLEAN |
getBooleanCellValue() |
boolean |
| 5 | CELL_TYPE_ERROR |
getErrorCellvalue() |
byte |
이번시간에는 POI 프로젝트를 이용하여 엑셀 파일을 읽어보았습니다.
다음 시간에는 엑셀파일에 쓰는 핸드링을 해 보도록 하지요~
| 네이버 | ![]() |
| |||
| http://blog.naver.com/levin01/100011050010 | |||
|
Jakarta POI VII. 엑셀 쓰기예제 쓰기도 역시 읽기와 비슷합니다. ① 엑셀 워크북을 생성합니다. 행과 셀을 생성하려면 당연한 절차겠죠? HSSFWorkbook workbook = new HSSFWorkbook(); ② 시트를 생성합니다. 시트명을 파라미터로 바로 생성 합니다. HSSFSheet sheet = workbook.createSheet("sheet name"); 만약 한글로 시트명을 만들려면 다음과 같이 인코딩이 필요합니다. HSSFSheet sheet = workbook.createSheet(); workbook.setSheetName( 0 , "한글" , HSSFWorkbook.ENCODING_UTF_16 ); ③ 셀에 사용할 스타일을 미리 생성해 둡니다. HSSFCellStyle style = wb.createCellStyle(); 등 여러가지 스타일을 만들 수 있습니다. 스타일은 다음 주소를 참고하세요 http://jakarta.apache.org/poi/apidocs/org/apache/poi/hssf/usermodel/HSSFCellStyle.html ④ 로우를 하나 생성합니다. HSSFRow row = sheet.createRow(0); ⑤ 셀츨 하나 생성하여 스타일을 주고 값을 입력합니다. HSSFCell cell = row.createCell((short)0); cell.setCellStyle(style); cell.setCellValue("jakarta project!"); 만약 한글을 입력한다면 인코딩 해야 하며 값 세팅전에 해야 합니다. cell.setEncoding(HSSFCell.ENCODING_UTF_16); //한글 처리 cell.setCellStyle(style); cell.setCellValue("자카드타 프로젝트!"); ⑥ 모든 셀이 다 입력되었으면 파일을 만듭니다. FileOutputStream fs = new FileOutputStream("excelfile.xls"); VIII. 쓰기샘플 소스
자 결과화면 입니다. 성공! 위의 소스를 기본으로 한다면 그리 어렵지 않을겁니다 ^^ 참고로 셀병합은 HSSFWorkbook wb = new HSSFWorkbook(); | |||
| 네이버 | ![]() |
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| http://blog.naver.com/levin01/100012095949 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Jakarta POI IX. Cell을 좀더 유연하게! 1. Date타입 셀 만들기 ① 소스 ② 결과 ③ HSSFDateFormat이 지원하는 날짜 포맷 cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); 에서 다음과 같이 포맷을 정할 수 있다 (현재시간은 2005년 3월 14일 0시 52분 17초.. 헛 화이트데이 --;) 2. Cell의 Align속성 ① 소스 ② 결과 3. Cell의 Border 속성 ① 소스 ② 결과 ③ HSSFCellStyle HSSFCellStyle에는 다음과 같은 static 멤버변수가 존재합니다
4. Cell의 색갈 채우기 ① 소스② 결과 ③ HSSFColor 정리! 5. Cell 병합 ① 소스 ② 결과 ③ Region 특정셀을 합칠 때는 HSSFSheet의 addMergedRegion(Region region)와 합칠 셀의 영역을 나타내는 Region을 사용한다. Region region = new (int 시작ROW, short 시작COL, int 종료ROW, short 종료COL); 6. Cell에 폰트 설정하기 ① 소스 ② 결과 ============================================= 본문서는 자유롭게 배포/복사 할수 있지만 이문서의 저자에 대한 언급을 삭제하시면 안됩니다 저자 : GoodBug (unicorn@jakartaproject.com) 최초 : http://www.jakartaproject.com ============================================= | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 네이버 | ![]() |
| |||
| http://blog.naver.com/levin01/100017355281 | |||
|
Jakarta POI
X. 이미지 민군 : 유니콘홈피에서 퍼왔습니다 허락없이 퍼온점 죄송하게 생각하고 저작권이 문제될경우 즉시삭제하겠습니다 보시는분들 주의해주시길 부탁드립니다 POI 3.0 부터 드디어 이미지를 지원하는군요. 아직 알파버젼이구요 http://www.apache.org/dyn/closer.cgi/jakarta/poi/ 에서 최신버젼을 다운 받을 수 있습니다 최신링크 http://mirror.apache.or.kr/jakarta/poi/dev/bin/poi-bin-3.0-alpha1-20050704.zip 아래 소스는 OKJSP의 "이루"님이 작성한 소스입니다 from http://www.okjsp.pe.kr/bbs?act=VIEW&seq=60543&bbs=bbs4&keyfield=content&keyword=&pg=0 | |||
출처 : Tong - 반이오타님의 JAVA Programing통
| 정규식을 이용한 다양한 예제 (3) | 2010.05.16 |
|---|---|
| CallableStatement 사용하기 (0) | 2008.06.26 |
| Oracle의 Stored Procedure, Function 이용하기 (0) | 2008.06.26 |
| 소수점 연산 (0) | 2008.06.26 |
| Jakarta POI Excel File 읽기, 쓰기, 셀컨트롤, 이미지 삽입 (1) | 2008.06.26 |
댓글을 달아 주세요
시작하기 위해 내 배우자를 언급하고 새로운 설문 조사가 부가 확인란되고이 후 의견을 포함시킬 수 때 같은 검토를 고집 일부 메시지를 구입하는 동안 당신 - 알림을해서 교전이 동안. 아마 그러나 당신이 도움이됩니다 통해 멀리 데려다해야 있나요? 건배!
2012.01.29 14:32 [ ADDR : EDIT/ DEL : REPLY ]비밀댓글입니다
2012.04.10 04:07 [ ADDR : EDIT/ DEL : REPLY ]시작하기 위해 내 배우자를 언급하고 새로운 설문 조사가 부가 확인란되고이 후 의견을 포함시킬 수 때 같은 검토를 고집 일부 메시지를 구입하는 동안 당신 - 알림을해서 교전이 동안.
2012.11.23 11:59 [ ADDR : EDIT/ DEL : REPLY ]<a href='http://blogtegal.com' title='blog tutorial'>blog tutorial</a> <a href='http://blogtegal.com/2011/10/cara-membeli-hosting-hostgator.html'>membeli hosting hostgator</a> <a href='http://blogtegal.com/category/hosting'>hosting</a>
2013.02.06 23:41 [ ADDR : EDIT/ DEL : REPLY ]to very-very impressiv, ny0ng miki nemu nd0g lenggarangan sg kaya koen admin hehe
2013.02.06 23:46 [ ADDR : EDIT/ DEL : REPLY ]http://googlemin.blogspot.com
http://googlemin.blogspot.com/2013/01/bank-mandiri-bank-terbaik-di-indonesia.html