'Language/JAVA'에 해당되는 글 57건

  1. 2014.11.11 pageContext 내장 객체
  2. 2014.11.11 http://www.docjar.com/
  3. 2014.04.16 ReentrantReadWriteLock
  4. 2014.01.14 한글, 유니코드의 이해
  5. 2014.01.07 정적 변수 정적 메소드 (static) 1
  6. 2014.01.02 Java에서 System.getProperty() 2
  7. 2013.12.03 tomcat7 cach filter
  8. 2013.11.14 jdk7 file write
  9. 2013.11.13 double 지수 표현 제거
  10. 2013.11.13 POI를 이용한 Excel ( *.xls, *.xlsx ) 읽기

pageContext 내장 객체

Language/JAVA 2014. 11. 11. 14:12

- pageContext 객체는 현재 JSP 페이지의 컨텍스트(Context)를 나타내며, 주로 다른 내장 객체를 구하거나 페이지의 흐름 제어 그리고 에러 데이터를 얻어낼 때 사용된다.


- pageContext 내장 객체는 javax.servlet.jsp.PageContext 객체 타입으로 ,JSP에서는 pageContext 객체로 사용된다.


- pageContext 내장 객체의 메소드


 메소드

설명 

 ServletRequest getRequest()

페이지 요청 정보를 가지고 있는 request 내장 객체를 리턴한다. 

ServletResponse getResponse() 

페이지 요청에 대한 응답 정보를 가지고 있는 response 내장 객체를 리턴한다. 

JSPWriter getOut() 

페이지 요청에 대한 출력 스트림인 out 내장 객체를 리턴한다. 

HttpSession getSessoin() 

요청한 웹 브라우저의 세션 정보를 담고 있는 session 내장 객체를 리턴한다. 

ServletContext getServletContext() 

페이지에 대한 서블릿 실행 환경 정보를 담고 있는 application 내장 객체를 리턴한다. 

Object getPage() 

page 내장 객체를 리턴한다. 

ServletConfig getServletConfig() 

해당 페이지의 서블릿 초기 정보 설정 정보를 담고 있는 config 내장 객체를 리턴한다. 

Exception getException() 

페이지 실행 중에 발생되는 에러 페이지에 대한 예외 정보를 갖고 있는 exception 내장 객체를 리턴한다. 



<%


JSPWriter outObject = pageContext.getOut();        // out 내장 객체 리턴


%>

'Language > JAVA' 카테고리의 다른 글

Class.getResource vs. ClassLoader.getResource  (0) 2014.11.14
[Apache Commons]Configuration  (0) 2014.11.11
http://www.docjar.com/  (0) 2014.11.11
ReentrantReadWriteLock  (0) 2014.04.16
한글, 유니코드의 이해  (0) 2014.01.14
:

http://www.docjar.com/

Language/JAVA 2014. 11. 11. 14:09

http://www.docjar.com/

'Language > JAVA' 카테고리의 다른 글

[Apache Commons]Configuration  (0) 2014.11.11
pageContext 내장 객체  (0) 2014.11.11
ReentrantReadWriteLock  (0) 2014.04.16
한글, 유니코드의 이해  (0) 2014.01.14
정적 변수 정적 메소드 (static)  (1) 2014.01.07
:

ReentrantReadWriteLock

Language/JAVA 2014. 4. 16. 15:30

Example of ReentrantReadWriteLock in Java

December 17, 2012

ReentrantReadWriteLock implements ReadWriteLock which has both type of lock read lock and write lock. More than one thread can apply read lock simultaneously but write lock can be applied by one thread at one time. As an example of lock is that collection that is being accessed by more than one thread may need to modify the collection frequently. So threads will need to apply locks on that collection object. ReadWriteLock has only two method readLock and writeLock. readLock() is used for reading and writeLock() is used for writing. ReentrantReadWriteLock has the following properties.
1. ReentrantReadWriteLock has no preferences over the selection of readLock and writeLock. 
2. readLock cannot be acquired until all writeLock is released. 
3. It is possible to downgrade writeLock to readLock but vice-versa is not possible. 

Find the example of ReentrantReadWriteLock in a custom bean in concurrent environment. Let�s we have a MyBean class in which we have methods like add, get and delete.

  1. package com.concretepage;
  2.  
  3. import java.util.concurrent.locks.Lock;
  4. import java.util.concurrent.locks.ReentrantReadWriteLock;
  5.  
  6. public class MyBean {
  7. private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
  8. private final Lock r = rwl.readLock();
  9. private final Lock w = rwl.writeLock();
  10. private String data;
  11.  
  12. public String getData() {
  13. r.lock();
  14. try{
  15. return data;
  16. }finally{
  17. r.unlock();
  18. }
  19. }
  20.  
  21. public void setData(String data) {
  22. w.lock();
  23. try{
  24. this.data = data;
  25. }finally{
  26. w.unlock();
  27. }
  28. }
  29. }

참조 - http://www.concretepage.com/java/example_readwriteLock_java

'Language > JAVA' 카테고리의 다른 글

pageContext 내장 객체  (0) 2014.11.11
http://www.docjar.com/  (0) 2014.11.11
한글, 유니코드의 이해  (0) 2014.01.14
정적 변수 정적 메소드 (static)  (1) 2014.01.07
Java에서 System.getProperty()  (2) 2014.01.02
:

한글, 유니코드의 이해

Language/JAVA 2014. 1. 14. 12:54

http://ericooool.blogspot.kr/2013/04/blog-post.html


http://helloworld.naver.com/helloworld/76650

'Language > JAVA' 카테고리의 다른 글

http://www.docjar.com/  (0) 2014.11.11
ReentrantReadWriteLock  (0) 2014.04.16
정적 변수 정적 메소드 (static)  (1) 2014.01.07
Java에서 System.getProperty()  (2) 2014.01.02
tomcat7 cach filter  (0) 2013.12.03
:

정적 변수 정적 메소드 (static)

Language/JAVA 2014. 1. 7. 11:10

자바의 정적변수(static variables)와 정적메소드(static methods)



오늘은 static 키워드를 쓰는 자바의 정적변수(Class Variables)와 정적메소드(Class Methods)에 대해서 알아보기로 하자. 자바를 조금 배운 이들이라면 아마 이 단어만 나와도 벌써부터 고개를 설레설레 흔든다던지 잠시 이 장은 그냥 건너뛰고 나중에 보자고 미룰지도 모르겠다. 허나 오늘만큼은 특히 그러는 이가 없기를 바란다. 나중으로 미루는 이들은 먼훗날 두고두고 땅을 치며 후회하는 일이 있을지도 모른다. 왜 조금더 일찍 이 강좌를 보지 않았느냐고 말이다.ㅎㅎ static은 우리가 맨처음(메인메소드?) 접하는 키워드 중에 하나인데도 불구하고 오랜 시간동안 자바를 쓰면서도 생소하고 낯설게 느끼는 이들이 많은데 그 쓰임이 아주 단순하지만은 않기 때문일 것이다. 객체생성없이 접근할수 있게 만드는 명령어가 static이라 메인메소드 앞에 항상 static이란 키워드를 붙여온 것인데 자세한 이유는 오늘 강좌를 공부하면 자연히 알게 될것이다.^^


자바의 static 키워드를 통해 전체적인 프로그램의 구성에 대해서 여러분은 다시 한번 생각하는 기회를 갖게 될것이다. 필자는 모든 강좌의 설명을 요약식이 아닌 서술식으로 풀이하고 있는데 이런 방식을 택한 까닭은 내용이 같을지라도 다양하고 다채로운 표현을 통해 여러분의 사고와 이해를 높이기 위한 것이니 여기에 딴지거는 이(?)가 없길 바란다. 특히 이번 강좌는 static이란 단어부터가 심상치 않으므로 얼마나 내용이 길어질지는 장담할수가 없다. 불만에 대비해 미리 방어벽치는 중이다.ㅎㅎ 일단 static이란 단어를 지칭하는 방법이 여러가지라 더 혼란을 가중시키고 있지 않냐는게 필자의 생각이다. 시작하기에 앞서 자바의 정적변수와 정적메소드에 대한 용어들부터 살펴보자.


정적 변수

=static variables(static fields)

=class variables

=클래스 변수

예제)   static int a;


정적 메소드

=static methods

=class methods

=클래스 메소드

예제)   static void move( ) {...}


정적 변수와 정적 메소드를 통틀어서 Static Members 라고 하기도 한다. 이렇게 정리하고 보니 우리가 흔히 쓰는 일반 변수와 일반 메소드도 여러가지 다른 용어로 많이 쓰이는데 말나온김에 비교할겸 적어보기로 하겠다.


일반 변수

=instance variables

=인스턴스 변수

=멤버 변수

=필드 변수

예제)   int a;


일반 메소드

=instance methods

=인스턴스 메소드

=멤버 메소드

=필드 메소드

예제)   void move( ) {...}


위의 단어들을 몰라서 애를 먹는걸 방지하고자 한번 적어봤다. 필자는 문맥의 통일성을 위해 분류별로 가장 상위에 있는 용어(정적변수,정적메소드,일반변수,일반메소드)만 쓰기로 하겠다. 아무래도 서로 계속 비교를 해가면서 설명을 해야될듯한 묘한 예감(?)이 들기에 오늘 강좌는 용어만 통일해서 설명해도 여러분이 강좌를 이해하는데 많은 시간과 에너지를 절약하게 되리라 본다.^^


정적변수와 정적메소드라고 하니 아주 거창한걸 기대(?)했을지 모르겠지만 정적변수와 정적메소드라 함은 위와 같이 일반변수와 일반메소드 앞에 static 키워드를 써놓은 것을 말한다. 정적변수의 경우 객체를 아무리 많이 만들어도 해당변수는 하나만 존재한다. 일반 변수의 경우 객체가 생성될때마다 새롭게 생성되어 쓰이나 정적변수는 이와는 다르게 처음에 한번만 생성되고 공유해서 사용한다. static이란 클래스가 로딩될때 메모리 공간을 할당하는데 이 결정된 공간이 변하지 않으므로 정적이라는 표현을 쓴다. 메모리에 로딩 즉 메모리 공간을 확보해야 해당멤버를 쓸수가 있는데 자바는 프로그램을 실행하면 클래스가 우선 메모리에 로딩되나 static은 이보다 먼저 메모리에 로딩되어진다. 일반변수는 객체가 생성될때마다 메모리 공간이 할당되나 static의 경우 클래스가 메모리에 로딩되기전 이미 정적변수와 정적메소드를 위한 메모리 공간이 할당되므로 객체가 생성될때마다 메모리 공간이 할당되지 않는다.


이런 까닭에 static에 대한 장점을 크게 두가지로 나눌수 있다. 첫째로, static을 쓴 변수나 메소드는 객체생성없이 모든 객체가 아무런 제약없이 공유할수 있다. 물론 객체생성하고 써도 상관없다. 둘째로, static을 쓴 변수는 값을 공유하므로 연속적으로 그 값의 흐름을 이어갈수 있다는 것이다. 다시 말해서 일반변수는 객체생성시마다 그 값이 초기화되지만 정적변수는 객체생성을 하지 않으므로 다른 객체에서 계속적으로 이어서 그 값을 변화시킬수 있는 것이다. 이에 대한 부분은 예제를 보면 쉬울 것이다. 앞전에 배운 final이란 키워드를 함께 사용하면(static final double PI = 3.141592653589793;) 공유는 하면서 값은 고정시킬수 있는데 보통 상수가 이에 해당한다. 말나온김에 잠깐 상수에 대해서 언급하고 계속 진행하겠다. 자바에서 상수(Constant Value)를 쓸때 보통 아래처럼 static과 final을 함께 사용한다. 상수는 항상 변하지 않는 고유한 속성을 지닌 멤버니까 말이다.


(접근지정자) static final 자료형 상수명=상수값;

public static final double PI = 3.141592653589793;

static final double PI = 3.141592653589793;


상수의 경우 편리성을 위해 예제(PI)처럼 이름을 소문자가 아닌 대문자로 표기하는데 한단어가 아닌 여러단어로 이루어질 경우 전부 대문자이면 분간이 어려우므로 단어 사이마다 _(underscore)로 연결시키는게 관례다.


다시 돌아와서 보충설명을 이어서 해보도록 하겠다. 정적변수나 정적메소드를 쓰는 예제는 아래와 같다.


클래스명.a=100;   //객체생성없이 클래스명으로 정적변수에 접근가능

객체명.a=100;   //물론 객체생성후 얻은 인자로도 정적변수에 접근가능


클래스명.move( );   //객체생성없이 클래스명으로 정적메소드에 접근가능

객체명.move( );   //물론 객체생성후 얻은 인자로도 정적메소드에 접근가능


정적변수나 정적메소드를 호출하는 방법은 위와 같으며 같은 클래스내에서는 클래스명을 생략하고 써도 무방하다. 일반메소드 안에서는 객체생성없이 정적변수나 정적메소드를 호출할수 있으나 static을 쓰는 정적메소드 안에서는 객체생성없이 일반변수나 일반메소드를 호출할수가 없다. 이유는 이미 위에서 메모리에 관련해 설명한 것처럼 static멤버들이 먼저 로딩되므로 아직 만들어지지않은 객체의 변수나 메소드를 참조해서 쓸수는 없기 때문이다. 따라서 this라는 키워드도 정적메소드안에서는 사용이 불가능하며 메소드안에서 쓰이는 지역변수에도 사용할수 없다. 반대로 당연하지만 일반메소드안에서는 정적변수나 정적메소드를 쓸수가 있다. 이미 로딩된 static멤버들을 쓰지 못할 이유가 없기 때문이다.


우리가 저번 시간에 abstract 추상메소드에 대해서 공부한바 있다. 여기에는 static을 쓸수가 있을까? 당연히 불가능하다. static은 객체생성 없이도 호출이 가능한 키워드인데 내용이 없으면 안된다. 우리가 예전에 배운 초기화 블록(클래스안에 {...} 괄호만 있는 형태)을 기억하는가? static도 초기화 블록처럼 정적변수와 정적메소드를 초기화시킬수 있는 공간을 클래스안 어느 위치에서나 갯수에 구애받지않고 아래와 같이 만들수 있는데 이를 정적 초기화 블록(Static Initialization Blocks)이라고 부른다. 정적초기화블록은 클래스 로딩될때 자동으로 작동되며 초기화 블록에다가 아래처럼 static만 첨가한 형태이다.


static

{

... //정적변수나 정적메소드만 쓸수 있다.

...... //초기화시키고 싶은 내용 아무거나 쓰면 된다.

System.out.println("static {...}은 쓰는데 갯수 제한없다");

}


static 키워드가 어떻게 쓰이는지 알아보았는데 아직도 잘 모르겠다하는 이들이 있을지도 모르겠다. 괜찮다. ^^ 그런 이들을 위해 준비했다. 아주 자세하게 그리고 촘촘하게 예제를 만들었다. 여기를 누르고 다운받아 실행하기전에 본인이 생각한 결과를 먼저 적어보고 맞춰보기 바란다. 주석을 아주 풍부하게 실어놨으므로 본 강좌에서 이해못한 부분이 있더라도 자연스럽게 예제를 통해서 이해가 될것이다. static은 이곳저곳에서 많이 쓰이므로 코드 해석을 위해서라도 반드시 쓰는 용법을 알아두어야 한다. 예제의 결과는 아래와 같다.


moveA 메소드입니다

처음에 위치한 static{ }입니다

moveA 메소드입니다

끝에 위치한 static{ }입니다

10

10

moveA 메소드입니다

moveA 메소드입니다

12

12

=====1=====

10

moveB 메소드입니다

11

=====2=====

12

12

0

0

=====3=====

111

111

222

0


잠시 예제에 대한 간략한 설명을 하자면 static 블록이 어디에 위치하든 가장 먼저 실행됨을 알수있다. 그리고 맨밑에 3번 분리선후에 출력되는 결과값은 객체생성에 관련된 정적변수와 일반변수간의 어떤 차이가 있는지 비교가능하게 되어있다. 예제에서 정적변수a는 각 인스턴스마다 값(111)을 공유하므로 출력결과가 같으나 일반변수b는 각 인스턴스마다 새롭게 b를 생성하므로 값이 다름을 알수있다.


위에서 공부한바와 같이 static을 쓰면 객체생성을 하지 않아도 되니 여러모로 편리하고 메소드를 호출하는 시간이 짧아져 효율적이고 속도도 빠르다. 이런 장점이 있기 때문에 메소드안에서 일반변수를 사용하지 않아도 되는 경우나 인자가 공통된 값을 유지할 필요가 있다면 static을 붙이는 것을 고려해볼 필요가 있다. 이렇게 좋은 점이 있긴하나 그렇다고 해서 모든걸 static으로 만들수는 없다. 클래스에서 일반변수중 모든 객체에서 공유하고 유지해야될 값이 없거나 일반변수나 일반메소드를 수시로 쓰는 상황이라면 굳이 static을 써서 가독성을 떨어뜨릴 필요는 없기 때문이다. 모든건 상황에 따라 대처해야하는데 그런건 개발자(?)의 역량에 달려있지 않겠나 생각된다. 힘들겠지만 잠시 쉬었다가 복습하는 착한 프로그래머(?)가 되길 바라면서 오늘은 이만 마치겠다. ^^



Test42.java



출처 - http://alecture.blogspot.kr/2011/05/static-variables-static-methods.html

'Language > JAVA' 카테고리의 다른 글

ReentrantReadWriteLock  (0) 2014.04.16
한글, 유니코드의 이해  (0) 2014.01.14
Java에서 System.getProperty()  (2) 2014.01.02
tomcat7 cach filter  (0) 2013.12.03
jdk7 file write  (0) 2013.11.14
:

Java에서 System.getProperty()

Language/JAVA 2014. 1. 2. 15:54


System.getProperty 정리  JAVA / 컴퓨터 

2011/01/19 15:20

복사http://blog.naver.com/hopefuldream/140122065117

전용뷰어 보기

프로그램을 작성하다 보면  운영체제(OS)나 JVM 에 의존적인 정보를 알아야 할 때가 있다.

이때, System.getProperty(key) 메소드를 이용하여 각종 정보를 알수 있는데 key 부분에 알고자하는 키값을 넣으면 키에 해당하는 정보를

알려준다. 키는 아래와 같다.

키=값 형태로 나타나 있는데 앞에 있는 키를 넣으면 뒤에있는 값이 나온다는 말이다. 각자 시스템에 따라 다른값이 나온다.

예를들어 System.getProperty("java.vm.version"); 을 하면 1.5.0_18-b02 값이 반환된다.

 

java.runtime.name=Java(TM) 2 Runtime Environment, Standard Edition
sun.boot.library.path=C:\Program Files\Java\jdk1.5.0_18\jre\bin
java.vm.version=1.5.0_18-b02
java.vm.vendor=Sun Microsystems Inc.
java.vendor.url=http://java.sun.com/
path.separator=;
java.vm.name=Java HotSpot(TM) Client VM
file.encoding.pkg=sun.io
user.country=KR
sun.java.launcher=SUN_STANDARD
sun.os.patch.level=Service Pack 3
java.vm.specification.name=Java Virtual Machine Specification
user.dir=C:\java\client

java.runtime.version=1.5.0_18-b02
java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs=C:\Program Files\Java\jdk1.5.0_18\jre\lib\endorsed
os.arch=x86
java.io.tmpdir=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\
line.separator=

java.vm.specification.vendor=Sun Microsystems Inc.
user.variant=
os.name=Windows XP
sun.jnu.encoding=MS949
java.library.path=C:\Program Files\Java\jdk1.5.0_18\bin;

java.specification.name=Java Platform API Specification
java.class.version=49.0
sun.management.compiler=HotSpot Client Compiler
os.version=5.1
user.home=C:\Documents and Settings\Administrator
user.timezone=
java.awt.printerjob=sun.awt.windows.WPrinterJob
file.encoding=MS949
java.specification.version=1.5
user.name=Administrator
java.vm.specification.version=1.0
sun.arch.data.model=32
java.home=C:\Program Files\Java\jdk1.5.0_18\jre
java.specification.vendor=Sun Microsystems Inc.
user.language=ko
awt.toolkit=sun.awt.windows.WToolkit
java.vm.info=mixed mode, sharing
java.version=1.5.0_18
file.separator=\
java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport.cgi
sun.cpu.endian=little
sun.io.unicode.encoding=UnicodeLittle
sun.desktop=windows
sun.cpu.isalist=pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86

* property 확인 메소드

import java.util.Properties;
import java.util.Enumeration;

public class Test {
    public static void main(String[] args) {
        Properties props = System.getProperties();
        for(Enumeration en = props.propertyNames(); en.hasMoreElements();) {
            String key = (String)en.nextElement();
            String value = props.getProperty(key);
            System.out.println(key + "=" + value);
        }
    }

}

 

* 참고로 간혹 위에 없는 키값을 사용해서 당황해 하는 경우가 있다.

예를들어 위에는 전혀 없는 키값인데, System.getProperty("file.location.env"); 라면서 사용하는 경우가 있다.

이럴경우, JVM 의 VM arguments 부분을 살펴보면 다음과 같이 세팅되어 있다.

 -Dfile.location.env="C:\file\upload"

JVM의 VM arguments 는 JVM을 구동할때, 필요한 여러가지 값을 세팅하는 것인데 -D하고 바로뒤에 키="값"을 세팅하면

프로그램내에서 System.getProperty("키"); 를 통해 값을 가져올 수 있다.



Java에서 System.getProperty() 사용법


자바를 실행할 때, 실행되는 곳의 정보를 얻어오거나 운영체제의 정보가 필요할 때가 있습니다.

얼마전에 코드를 작성하면서 실행 위치에 있는 파일을 읽어드려야 하는데, 현재 위치를 알 수 있는 방법이 없을까 하고 찾아보니... System.getProperty()를 사용하여 쉽게 해결할 수 있었습니다.


1. System.getProperty 사용법


System.getProperty() 사용법은 간단합니다.
괄호 안에 주어진 특정 문자를 적어넣으면 그 값이 String 으로 출력됩니다.

예를 들어 실행하고 있는 현재 위치가 알고 싶다면 "user.dir" 이라고 적어주면 됩니다.

아래와 같이 "user.dir" 이라고 입력해봅니다.

String dir = System.getProperty("user.dir");
System.out.println(dir);


그 다음, 컴파일을 하면 아래와 같이 출력됩니다.

D:\Eclipse\eclipse-java-juno-win32\eclipse\workspace\test



2. Property 주요 검색어


검색어
java.versionJava 버전
java.vendorJava 공급자
java.vendor.urlJava 공급자 주소
java.homeJava를 설치한 디렉토리
java.class.versionJava 클래스 버전
java.class.pathJava 클래스 경로
java.ext.dir확장기능의 클래스 경로
os.name운영체제 이름
os.arch운영체제 아키텍처
os.version운영체제 버전 정보
file.separator파일 구분 문자
path.separator경로 구분 문자
line.separator행 구분 문자
user.name사용자 계정
user.home사용자 홈 디렉토리
user.dir현재 디렉토리


'Language > JAVA' 카테고리의 다른 글

한글, 유니코드의 이해  (0) 2014.01.14
정적 변수 정적 메소드 (static)  (1) 2014.01.07
tomcat7 cach filter  (0) 2013.12.03
jdk7 file write  (0) 2013.11.14
double 지수 표현 제거  (0) 2013.11.13
:

tomcat7 cach filter

Language/JAVA 2013. 12. 3. 19:06

http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#Expires_Filter


web.xml

<filter>
 <filter-name>ExpiresFilter</filter-name>
 <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
 <init-param>
    <param-name>ExpiresByType image</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>
 <init-param>
    <param-name>ExpiresByType text/css</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>
 <init-param>
    <param-name>ExpiresByType application/javascript</param-name>
    <param-value>access plus 10 minutes</param-value>
 </init-param>
</filter>
...
<filter-mapping>
 <filter-name>ExpiresFilter</filter-name>
 <url-pattern>/*</url-pattern>
 <dispatcher>REQUEST</dispatcher>
</filter-mapping>


'Language > JAVA' 카테고리의 다른 글

정적 변수 정적 메소드 (static)  (1) 2014.01.07
Java에서 System.getProperty()  (2) 2014.01.02
jdk7 file write  (0) 2013.11.14
double 지수 표현 제거  (0) 2013.11.13
POI를 이용한 Excel ( *.xls, *.xlsx ) 읽기  (0) 2013.11.13
:

jdk7 file write

Language/JAVA 2013. 11. 14. 13:21

How to write file using Files.newBufferedWriter?


package org.kodejava.example.nio;


import java.io.BufferedWriter;

import java.nio.charset.StandardCharsets;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;


public class FilesNewBufferedWriter {

    public static void main(String[] args) {

        Path logFile = Paths.get("D:\\Temp\\logs\\app.log");

        try (BufferedWriter writer = Files.newBufferedWriter(logFile,

                StandardCharsets.UTF_8, StandardOpenOption.WRITE)) {


            for (int i = 0; i < 10; i++) {

                writer.write(String.format("Message %s%n", i));

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}


출처 - http://kodejava.org/how-to-write-file-using-files-newbufferedwriter/




demoFilesOperations.groovy


  1. #!/usr/bin/env groovy  
  2. /** 
  3.  * demoFilesOperations.groovy 
  4.  * 
  5.  * Demonstrate some of the operations on files and directories provided by Java 
  6.  * SE 7 and its NIO.2 implementation. Specific focus is applied to the methods 
  7.  * of the java.nio.file.Files class and the java.nio.file.Path interface. 
  8.  */  
  9.   
  10. import java.nio.file.Files  
  11. import java.nio.file.Paths  
  12.   
  13. // 1. Acquire 'working directory' name to use as current directory.  
  14. def currentDirectoryName = System.getProperty("user.dir")  
  15.   
  16. // 2. Convert 'working directory' name plus a subdirectory named 'playarea' into  
  17. //    an instance of Path  
  18. def playAreaPath = Paths.get(currentDirectoryName, "playarea")  
  19. def playAreaStr = playAreaPath.toString()  
  20.   
  21. // 3. Create new subdirectory with name 'playarea'  
  22. def playAreaDirPath = Files.createDirectory(playAreaPath)  
  23.   
  24. // 4. Create a temporary directory with prefix "dustin_"  
  25. def tempDirPath = Files.createTempDirectory("dustin_")  
  26.   
  27. // 5. Create temporary files, one in the temporary directory just created and  
  28. //    one in the "root" temporary directory. Create them with slightly different  
  29. //    prefixes, but the same '.tmp' suffix.  
  30. def tempFileInTempDirPath = Files.createTempFile(tempDirPath, "Dustin1-"".tmp")  
  31. def tempFilePath = Files.createTempFile("Dustin2-"".tmp")  
  32.   
  33. // 6. Create a regular file.  
  34. def regularFilePath = Files.createFile(Paths.get(playAreaStr, "Dustin.txt"))  
  35.   
  36. // 7. Write text to newly created File.  
  37. import java.nio.charset.Charset  
  38. import java.nio.file.StandardOpenOption  
  39. Files.write(regularFilePath,  
  40.             ["To Be or Not to Be""That is the Question"],  
  41.             Charset.defaultCharset(),  
  42.             StandardOpenOption.APPEND, StandardOpenOption.WRITE)  
  43.   
  44. // 8. Make a copy of the file using the overloaded version of Files.copy  
  45. //    that expects two Paths.  
  46. def copiedFilePath =  
  47.    Files.copy(regularFilePath, Paths.get(playAreaStr, "DustinCopied.txt"))  
  48.   
  49. // 9. Move (rename) the copied file.  
  50. import java.nio.file.StandardCopyOption  
  51. def renamedFilePath = Files.move(copiedFilePath,  
  52.                                  Paths.get(playAreaStr, "DustinMoved.txt"),  
  53.                                  StandardCopyOption.REPLACE_EXISTING)  
  54.   
  55. // 10. Create symbolic link in 'current directory' to file in 'playarea'  
  56. def symbolicLinkPath = Files.createSymbolicLink(Paths.get("SomeoneMoved.txt"), renamedFilePath)  
  57.   
  58. // 11. Create (hard) link in 'current directory' to file in 'playarea'  
  59. def linkPath = Files.createLink(Paths.get("TheFile.txt"), regularFilePath)  
  60.   
  61. // 12. Clean up after myself: cannot delete 'playarea' directory until its  
  62. //     contents have first been deleted.  
  63. Files.delete(symbolicLinkPath)  
  64. Files.delete(linkPath)  
  65. Files.delete(regularFilePath)  
  66. Files.delete(renamedFilePath)  
  67. Files.delete(playAreaDirPath)  






import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

public class FileWriter2 {

public static void main(String[] args) {
Path file = null;
        BufferedWriter bufferedWriter  = null;
        try{
        String saveDir = "D:\\tmp\\";
String fileName = "app.log";
File mkDir = new File(saveDir); 
if(!mkDir.exists()){
mkDir.mkdirs();
}
            file = Paths.get(saveDir+fileName);
            List<String> raw1 = new ArrayList<String>();
       
raw1.add("1");                      
raw1.add("2");                    
raw1.add("3");  
 
            bufferedWriter = Files.newBufferedWriter(file, StandardCharsets.UTF_8,
            new OpenOption[] {StandardOpenOption.CREATE,StandardOpenOption.APPEND});
            
            bufferedWriter.write(String.format("%s%n", raw1.toString()));
 
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{
                bufferedWriter.close();
            }catch(IOException ioe){
                ioe.printStackTrace();
            }
        }
}
}


:

double 지수 표현 제거

Language/JAVA 2013. 11. 13. 17:27

import java.text.NumberFormat;


public class numberFormat {


public static void main(String[] args) {

// TODO Auto-generated method stub

double num = 1.2345E2;

NumberFormat f = NumberFormat.getInstance();

f.setGroupingUsed(false);

String val = f.format(num);

System.out.println(val);

}


}

:

POI를 이용한 Excel ( *.xls, *.xlsx ) 읽기

Language/JAVA 2013. 11. 13. 17:13


excel.zip



apache poi site :  http://poi.apache.org/


필요 Libraries

-- *.xls 을 위한 library

poi-3.7-20101029.jar

-- *.xlsx를 위한 libraries

poi-ooxml-3.7-20101029.jar
xmlbeans-2.3.0.jar
poi-ooxml-schemas-3.7-20101029.jar
ooxml-lib\dom4j-1.6.1.jar


-- 사용 ( Map 에 Data 저장 .. sample )

*.xls 의 경우 excel 파일 읽어오는 방법

POIFSFileSystem fileSystem = new POIFSFileSystem(new FileInputStream(new File(excelFile)));

SSFWorkbook work = new HSSFWorkbook(fileSystem);

int sheetNum = work.getNumberOfSheets();

 

log.error("\n# sheet num : " + sheetNum);

 

forint loop = 0; loop < sheetNum; loop++){

  HSSFSheet sheet = work.getSheetAt(loop);

 

  int rows = sheet.getPhysicalNumberOfRows();

 

  log.error("\n# sheet rows num : " + rows);

 

  forint rownum = 0; rownum < rows; rownum++){

    HSSFRow row = sheet.getRow(rownum);

   

    if(row != null){

      int cells = row.getPhysicalNumberOfCells();

     

      log.error("\n# row = " + row.getRowNum() + " / cells = " + cells);

     

      for(int cellnum =0; cellnum < cells; cellnum++){

        HSSFCell cell = row.getCell(cellnum);

       

        if(cell != null){

         

          switch (cell.getCellType()) {

         

          case HSSFCell.CELL_TYPE_FORMULA:

                 params.put("CELL_TYPE_FORMULA"+cellnum, cell.getNumericCellValue());

                 break;

                

          case HSSFCell.CELL_TYPE_STRING:

                 params.put("CELL_TYPE_STRING"+cellnum, cell.getStringCellValue());

                 break;

                

          case HSSFCell.CELL_TYPE_BLANK:

                 params.put("CELL_TYPE_BLANK"+cellnum, cell.getBooleanCellValue());

                 break;

                

          case HSSFCell.CELL_TYPE_ERROR :

                 params.put("CELL_TYPE_ERROR"+cellnum, cell.getErrorCellValue());

                 break;

         ......

          default:

                 break;

          }

        }

        log.error("\n CELL __ [params ] => " + params.toString());

      }

    }

  }

}



*.xlsx 의 경우 excel 파일 읽어오는 방법

XSSFWorkbook work = new XSSFWorkbook(new FileInputStream(new File(excelFile)));

int sheetNum = work.getNumberOfSheets();

 

log.error("\n# sheet num : " + sheetNum);

 

forint loop = 0; loop < sheetNum; loop++){

  XSSFSheet sheet = work.getSheetAt(loop);

 

  int rows = sheet.getPhysicalNumberOfRows();

 

  log.error("\n# sheet rows num : " + rows);

 

  forint rownum = 0; rownum < rows; rownum++){

    XSSFRow row = sheet.getRow(rownum);

   

    if(row != null){

      int cells = row.getPhysicalNumberOfCells();

     

      log.error("\n# row = " + row.getRowNum() + " / cells = " + cells);

     

      for(int cellnum =0; cellnum < cells; cellnum++){

        XSSFCell cell = row.getCell(cellnum);

       

        if(cell != null){

         

          switch (cell.getCellType()) {

         

          case XSSFCell.CELL_TYPE_FORMULA:

                 params.put("CELL_TYPE_FORMULA"+cellnum, cell.getNumericCellValue());

                 break;

                

          case XSSFCell.CELL_TYPE_STRING:

                 params.put("CELL_TYPE_STRING"+cellnum, cell.getStringCellValue());

                 break;

                

          case HSSFCell.CELL_TYPE_BLANK:

                 params.put("CELL_TYPE_BLANK"+cellnum, cell.getBooleanCellValue());

                 break;

                

          case XSSFCell.CELL_TYPE_ERROR :

                 params.put("CELL_TYPE_ERROR"+cellnum, cell.getErrorCellValue());

                 break;

          ...... 

          default:

                 break;

          }

        }

        log.error("\n CELL __ [params ] => " + params.toString());

      }

    }

  }

}



출처 - http://enosent.tistory.com/30



: