달력

02

« 2012/02 »

  •  
  •  
  •  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  •  
  •  
  •  
The Java Developers Almanac 1.4 책에 해당하는 소스 사이트이다.


구글에서 간단한 자바 소스를 찾다보면 많이 나오게 되는 사이트이다.
책의 내용을 본 적은 없지만 구글 검색 엔진 결과의 상위에 랭크가 되는 걸 보면 상당히 유용한 사이트이 인거 같다.

실제로 간단한 소스 코드가 잘 정리되어 있다.

TAG java
Posted by korcslewis
2009/07/15 17:43

Swing 튜토리얼 - JComponent Java SE2009/07/15 17:43

링크와 함께 원문을 실어 놓는다.
어디가에 계실 번역자님~~~ 글을 복사한 것에 따른 문의가 있으면 언제든지 연락주세요...
링크로 바꿀께요^^;; 다음에 원문을 혹시나 찾지 못할까봐ㅎㅎ

코드 분석을 위해 새삼스럽게 Java swing 쪽을 잠시 보고 있는데 나름 부담되었는데 도움이 되었다^^


출처 : http://java.sun.com/docs/books/tutorial/uiswing/components/jcomponent.html

JComponent클래스
최상위 컨테이너를 제외하고 이름이 J로 시작하는 모든 Swing콤포넌트는 JComponent클래스를 상속한다.
예를 들면, JPanel, JScrollPane, JButton, JTable등은 모두 JComponent클래스를 상속했다.
그러나, JFrame, JDialog는 그렇지 않은 데, 그것들은 최상위 컨테이너 이다.
JComponent클래스는 Container클래스를 상속하며, Container컨테이너 클래스는 다시 Component클래스를 상속한다.

Component클래스는 레이아웃 힌트를 제공하는 것부터 그리기, 이벤트를 제공하는 것까지 모든 것을 포함한다.

Container클래스는 콤포넌트를 컨테이너에 추가하고, 레이아웃을 설정하는 것을 지원한다.

이 문서의 API 표는 JComponent클래스 뿐만이 아니라, Component, Container클래스의 가장 자주 사용되는 메소드들을 요약했다.


JComponent클래스의 기능

JComponent클래스의 기능은 다음 카테고리로 나눌 수 있다.
  • 툴팁
  • 그리기와 테두리
  • 프로그램 전체에 영향을 끼치는 룩앤필
  • 사용자정의 속성
  • 레이아웃 지원
  • 노약자, 장애인을 위한 접근성 지원
  • 드랙앤드롭 지원
  • 이중 버퍼링
  • 키바인딩(Key bindings)
툴팁
setToolTipText메소드로 문자열을 지정하면, 콤포넌트 사용자에게 도움말을 제공할 수 있다.
커서가 콤포넌트 위에서 머물면, 콤포넌트 옆의 작은 창에 지정된 문자열이 보인다.
더  자세한 정보는 How to Use Tool Tips 을 참조한다.
그리기와 테두리
setBorder메소드는 콤포넌트가 가장자리에 보여주는 테두리를 설정할 수 있도록 한다.
콤포넌트 안쪽을 그리기 위해서는 paintComponent메소드를 오버라이드 하면 된다.
자세한 내용은 How to Use Borders와  Performing Custom Painting을 참조한다.
프로그램 전체에 영향을 끼치는 룩앤필
모든 JComponent객체는 그에 해당된는 ComponentUI객체를 가지고 있으며,
ComponentUI객체는 그리기와 이벤트 처리, 크기조절등의 역할을 행한다.
정확히 어떤 ComponentUI객체가 사용되는 지는 현재의 룩앤필에 따라 다르다.
UIManager.setLookAndFeel메소드를 사용해서 현재의 룩앤필을 설정할 수 있다.
자세한 내용은 How to Set the Look and Feel을 참조한다.
사용자정의 속성
모든 JComponent객체를 한 개 이상의 속성(이름/객체 쌍)과 연관시킬 수 있다.
예를 들면, 레이아웃 관리자는 속성을 사용해서 레이아웃 관리자가 관리하는 모든 콤포넌트와 제약 객체(constraints object)를 연관시킬 수 있다. putClientProperty메소드를 이용해서 속성을 설정하고, getClientProperty를 이용해서 속성을 가져온다.
속성에 대한 일반적인 정보를 얻고 싶으면 Properties를 참고한다.
레이아웃 지원
AWT의 Component클래스는 getPreferredSize, getAlignmentX와 같은 레이아웃 힌트 메소드는 제공하지만,  이러한 레이아웃 힌트를 설정할 수 있는 방법을 제공하지 않는다. JComponent클래스느 레이아웃 힌트를 설정하는 메소드를 제공한다. setMinimumSize, setMaximumSize, setAlignmentX, setAlignmentY 메소드가 그것이다.
더 자세한 정보는 Laying Out Components Within a Container를 참조한다.
노약자, 장애인을 위한 접근성 지원
JComponent클래스는 스크린 리더가 콤포넌트로부터 정보를 가져가는 것을 돕는 등의 접근기술을 도와주는 API와 기본기능이 있다.
How to Support Assistive Technologies을 참조한다.
드래그앤드드롭 지원
JComponent클래스는 콤포넌트의 이전 처리기(transfer handler)를 설정하는 API를 제공한다.
이전 처리기는 Swing 드래그앤드드롭의 기반이 된다.
자세한 사항은 Introduction to Drag and Drop and Data Transfer을 참조한다.
이중 버퍼링
이중 버퍼링(double buffering) 화면에서 부드러운 그리기 동작을 보여준다.
Performing Custom Painting을 참조한다.
키 바인딩
이 기능을 사용하면 사용자가 키보드의 특정 키를 누를 때 콤포넌트가 반응하도록 만들 수 있다.
예를 들면, 많은 룩앤필의 경우 버튼이 포커스를 가지고 있을 때, 스페이스 키를 누르는 것은 마우스로 클릭하는 것과 동일한 효과를 가진다. 룩앤필은 자동적으로 스페이스키를 누르는 것과 버튼의 결과적인 효과를 바인딩(결속) 시켜준다.
더 자세한 정보는 How to Use Key Bindings을 참조한다.

JComponent API

JComponent클래스는 많은 새로운 메소드를 제공하며, Component클래스와 Container클래스로부터 많은 메소드를 상속 받았다. 다음 표는 가장 많이 사용하는 메소드를 요약했다.
  • 콤포넌트 외양을 커스터마이징
  • 콤포넌트 상태를 설정하거나 가져오기
  • 이벤트 처리하기
  • 콤포넌트 그리기
  • 포함계층구조를 처리하기
  • 콤포넌트 레이아웃
  • 크기와 위치정보를 가져오기
  • 크기와 위치를 지정하기
콤포넌트 외양을 커스터마이스징
메소드용도
void setBorder(Border) 
Border getBorder()
콤포넌트의 테두리를 설정하거나 가져온다.
자세한 내용은 How to Use Borders 을 참조한다.
void setForeground(Color)
void setBackground(Color)
콤포넌트의 전면색상 혹은 배경색상을 설정한다.
전면색상은 주로 콤포넌트 안에 문자를 그려넣는 데 사용되는 색상이다. 배경색상은 콤포넌트가 불투명하다는 전제하에서 콤포넌트의 뒷배경영역의 색상이다.

Color getForeground() 
Color getBackground()
콤포넌트의 전면색상 혹은 배경색상을 가져온다.
void setOpaque(boolean) 
boolean isOpaque()
콤포넌트가 불투명(opaque)한지 여부를 설정하거나 가져온다.
불투명한 콤포넌트는 그 배경을 배경색상을 채워넣는다.
void setFont(Font) 
Font getFont()
콤포넌트의 글꼴을 설정하거나 가져온다.
만약 콤포넌트의 글꼴이 설정되지 않았다면, 부모콤포넌트의 글꼴이 반환된다.
void setCursor(Cursor)
Cursor getCursor()
커서를 갖다대었을 때 표시되는 커서모양을 설정하거나 가져온다. 예를 들면 aPanel.setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR));
콤포넌트의 상태 설정하기
메소드용도
void setComponentPopupMenu(String)JComponent객체의 JPopupMenu설정하기.
바인딩을 등록하고 필요한 리스너를 추가해서 적절한 타이밍에 JPopMenu객체가 보여지게 하는 것은 UI가 담당한다.
JPopMenu가 보여지는 시점은 룩앤필에 따라 다르다. 어떤 룩앤필은 마우스 이벤트에 보여줄 것이고, 어떤 이벤트는 키바인딩을 가능하게 할 것이다.
popup이 null이고, getIngeritsPopupMenu가 true를 반환하면, getComponentPopupMenu메소드는 부모객체로 위임될 것이다. 이 방식으로 자식 콤포넌트가 부모 콤포넌트의 popupmenu를 상속할 수 있다.
void setTransferHandler(TransferHandler)
TransferHandler getTransferHandler()
transferHandler속성을 설정하거나 제거한다.
TransferHandler는 드래그앤드드롭 혹은 클립보드 로 (부터)의 잘라내기, 복사, 붙여넣기를 통해서 데이터를 교환하는 것을 지원한다.
더 자세한 내용은 Introduction to Drag and Drop and Data Transfer을 참조한다.
void setToolTipText(String)툴팁에 보여줄 문자열을 설정한다.
더 많은 정보는 How to Use Tool Tips을 참조한다.
void setName(String) 
String getName()
콤포넌트의 이름을 설정하거나 가져온다.
이  메소드는 텍스트를 표시하지 않는 콤포넌트와 문자열을 연결시킬 때 유용할 수 있다.
boolean isShowing()콤포넌트가 화면에 보여지는 지를 결정한다.
이것의 의미는 콤포넌트가 visible이어야 하고, visible하고 show된 컨테이너에 포함되어야 한다는 의미이다.
void setEnabled(boolean) 
boolean isEnabled()
콤포넌트가 활성화 여부를 설정하거나 가져온다.
활성화된 콤포넌트는 사용자 입력에 반응하고 이벤트를 생성할 수 있다.
void setVisible(boolean) 
boolean isVisible()
콤포넌트가 visible인지를 설정하고 가져온다.
최상위 콤포넌트를 제외한 모든 콤포넌트는 초기값으로 visible하다.
이벤트 처리
(자세한 사항은
Writing Event Listeners을 참조한다.)
메소드용도
void addHierarchyListener(hierarchyListener l) 
void removeHierarchyListener(hierarchyListener l) 
계층구조가 변경되었다는 이벤트를 처리하기 위한 지정된 hierarchy listener를 추가하거나 제거한다.
리스너가 null이면, 예외를 발생시키지 않으며, 아무런 행동도 취해지지 않는다.
void addMouseListener(MouseListener) 
void removeMouseListener(MouseListener)
마우스 리스너(mouse listener)를 추가하거나 제거한다.
마우스 리스너는 사용자가 마우스를 사용해서 콤포넌트와 상호작용을 할 때 통보받는다.
void addMouseMotionListener(MouseMotionListener) 
void removeMouseMotionListener(MouseMotionListener)
마우스 동작 리스너(mouse motion listener )를 추가하거나 제거한다.
마우스 동작 리스너� 사용자가 해당 콤포넌트 안엣 마우스커서를 움직일 대 통보받는다.
void addKeyListener(KeyListener) 
void removeKeyListener(KeyListener)
키 리스터(key listener)를 추가하거나 제거한다.
키 리스너는 콤포넌트가 키보드 포커스를 가지고 있고, 사용자가 키보드를 타이핑하면 통보받는다.
void addComponentListener(ComponentListener) 
void removeComponentListener(ComponentListener)
콤포넌트 리스너(component listener )를 추가하거나 제거한다.
콤포넌트 리스너는 콤포넌트가  숨겨지거나, 보여지거나, 이동하거나, 크기변경이 될 때 통보받는다.
boolean contains(int, int) 
boolean contains(Point)
지정된 점(point)가 콤포넌트 내부에 있는 지 결정한다.
파라메터는 콤포넌트 좌표 시스템으로 지정되어야 한다.
정수값은 각각 x, y값을 나타낸다.
Component getComponentAt(int, int)
Component getComponentAt(Point)
입력된 x, y지점을 포함하는 콤포넌트를 반환한다.
만약 콤포넌트가 겹쳐져 있다면 가장 왼쪽위 콤포넌트를 반환한다.
이것은 Component.contains()메소드의 인덱스가 0에 제일 가까운 콤포넌를 찾아내는 것으로 결정한다.
Component setComponentZOrder(component comp, int index)
지정된 콤포넌트를 컨테이너의 지정된 z축 인덱스로 이동시킨다.

만약 콤포넌트가 다른 컨이너의 자식객체이면, 그 콤포넌트는 이 컨테이너에 추가되기 전에 이전의 컨테이너에서 제거된다.
java.awt.Container.add(Component, int)메소드와 중요한 차이점은 이 메소드는 이전 컨테이너에서 콤포넌트를 제거할 때, 허용되고 필요하지 않다면 removeNotify메소드를 호출하지 않는다는 것이다. 이 방식으로 만약 콤포넌트가 키보드 포커스를 가지고 있다면, 새로운 위치로 이동했을 때에도 키보드 포커스를 유지한다.

참고:  z축은  콤포넌트가 그려지는 순서를 결정한다. z축 값이 제일 큰 콤포넌트가 먼저 그려지고, 낮은 z축 값이 가장 낮은 콤포넌트가 가장 늦게 그려진다. 콤포넌트가 겹쳐진다면, z축 값이 낮은 콤포넌트가 z축 값이 높은 콤포넌트 위에 그려진다.

Component getComponentZOrder(component comp)
컨테이너 내부의 콤포넌트의 z축 값을 반환한다. z축에서 위에 있을 수록 인덱스 값은 낮다.
z축 값이 가장 낮은 콤포넌트는 가장 늦게 모든 자식 콤포넌트 위에 그려진다.
콤포넌트 그리기
(자세한 사항은
Performing Custom Painting을 참조한다.)
메소드용도
void repaint() 
void repaint(int, int, int, int)
콤포넌트의 전체가 다시 그려지도록 요청한다.
4개의 int형 파라메터는 다시 그릴 경계선을 지정하며, x, y, 폭, 높이를 의미한다.
void repaint(Rectangle)콤포넌트 내의 지정된 영역이 다시 그려지도록 요청한다.
void reval!idate()콤포넌트와 해당 컨테이너가 레이아웃을 다시 잡도록 요청한다. 콤포넌트가 visible된 이후에 명시적으로 크기조절, 정열 힌트 변경 조절, 포함계층구조 변경등을 하지 않았다면 이 메소드를 호출할 필요할 필요가 없다.
reval!idate메소드를 호출한 다음에는 항상 repaint메소드를 호출하도록 한다.
void paintComponent(Graphics)콤포넌트를 그린다.
이 메소드를 오버라이드해서 사용자정의 콤포넌트의 그리기를 구현한다.
포함계층구조 다루기
(더 자세한 내용은 최상위 컨테이너를 참조한다.
)
메소드
용도
Component add(Component) 
Component add(Component, int) 
void add(Component, Object)
지정된 콤포넌트를 이 컨테이너에 추가한다. 파라메터가 1개  사용되는 것은 콤포넌트를 컨테이너의 끝에 추가한다. int형 파라메터는 컨테이너 내의 새로운 콤포넌트의 위치를 표시한다. Object형 파라메터는 현재의 레이아웃 관리자에게 레이아웃 제한을 제공한다.
void remove(int) 
void remove(Component)
void removeAll()
이 컨테이너에서 1개 혹은 모든 콤포넌트를 제거한다.
int형 파라메터는 콤포넌트를 제거할 컨테이너 내부의 위치를 나타낸다.
JRootPane getRootPane()Get the root pane that contains the component.
Container getTopLevelAncestor()Get the topmost container for the component — a Window, Applet!, or null if the component has not been added to any container.
Container getParent()Get the component's immediate container.
int getComponentCount()Get the number of components in this container.
Component getComponent(int) 
Component[] getComponents()
Get the one of or all of the components in this container. The int argument indicates the position of the component to get.
Component getComponentZOrder(int)
Component[] getComponentZOrder()
Returns the z-order index of the component inside the container. The higher a component is in the z-order hierarchy, the lower its index. The component with the lowest z-order index is painted last, above all other child components.
Laying Out Components 
(see
Laying Out Components Within a Container for more information)
MethodPurpose
void setPreferredSize(Dimension) 
void setMaximumSize(Dimension) 
void setMinimumSize(Dimension)
Set the component's preferred, maximum, or minimum size, measured in pixels. The preferred size indicates the best size for the component. The component should be no larger than its maximum size and no smaller than its minimum size. Be aware that these are hints only and might be ignored by certain layout managers.
Dimension getPreferredSize() 
Dimension getMaximumSize() 
Dimension getMinimumSize()
Get the preferred, maximum, or minimum size of the component, measured in pixels. Many JComponent classes have setter and getter methods. For those non-JComponent subclasses, which do not have the corresponding setter methods, you can set a component's preferred, maximum, or minimum size by creating a subclass and overriding these methods.
void setAlignmentX(float) 
void setAlignmentY(float)
Set the alignment along the x- or y- axis. These values indicate how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, and 0.5 is centered, and so on. Be aware that these are hints only and might be ignored by certain layout managers.
float getAlignmentX() 
float getAlignmentY()
Get the alignment of the component along the x- or y- axis. For non-JComponent subclasses, which do not have the corresponding setter methods, you can set a component's alignment by creating a subclass and overriding these methods.
void setLayout(LayoutManager) 
LayoutManager getLayout()
Set or get the component's layout manager. The layout manager is responsible for sizing and positioning the components within a container.
void applyComponentOrientation(ComponentOrientation)void setComponentOrientation(ComponentOrientation)Set the ComponentOrientation property of this container and all the components contained within it. See Setting the Container's Orientation for more information.
Getting Size and Position Information 
MethodPurpose
int getWidth() 
int getHeight()
Get the current width or height of the component measured in pixels.
Dimension getSize() 
Dimension getSize(Dimension)
Get the component's current size measured in pixels. When using the one-argument version of this method, the caller is responsible for creating the Dimension instance in which the result is returned.
int getX() 
int getY()
Get the current x or y coordinate of the component's origin relative to the parent's upper left corner measured in pixels.
Rectangle getBounds()
Rectangle getBounds(Rectangle)
Get the bounds of the component measured in pixels. The bounds specify the component's width, height, and origin relative to its parent. When using the one-argument version of this method, the caller is responsible for creating the Rectangle instance in which the result is returned.
Point getLocation() 
Point getLocation(Point) 
Gets the current location of the component relative to the parent's upper left corner measured in pixels. When using the one-argument version of getLocation method, the caller is responsible for creating the Point instance in which the result is returned.
Point getLocationOnScreen()Returns the position relative to the upper left corner of the screen.
Insets getInsets()Get the size of the component's border.
Specifying Absolute Size and Position 
(see
Doing Without a Layout Manager (Absolute Positioning) for more information)
MethodPurpose
void setLocation(int, int) 
void setLocation(Point)
Set the location of the component, in pixels, relative to the parent's upper left corner. The twoint arguments specify x and y, in that order. Use these methods to position a component when you are not using a layout manager.
void setSize(int, int) 
void setSize(Dimension)
Set the size of the component measured in pixels. The two int arguments specify width and height, in that order. Use these methods to size a component when you are not using a layout manager.
void setBounds(int, int, int, int) 
void setBounds(Rectangle)
Set the size and location relative to the parent's upper left corner, in pixels, of the component. The four int arguments specify x, y, width, and height, in that order. Use these methods to position and size a component when you are not using a layout manager.
Posted by korcslewis
Android 개발시 apache http client 모듈을 이용할 경우 HttpClient 클래스를 이용하여 다음과 같이 GET/POST 메소드로 전송할 수 있다. 즉, HTTP로 요청할 수 있다.
일단 간단한 소스 코드를 살펴보자.

HttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet("http://www.daum.net");

method.setHeader("User-Agent", "Android emulator");

HttpResponse res = null;
try {
res = client.execute(method);
StatusLine status = res.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK) {
System.out.println("Method completed");
} else {
System.err.println("Method failed: " + status.getReasonPhrase());
}
}  catch ( ClientProtocolException e ) {
        // TODO Auto-generated catch block
        e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
}

일단, 위의 소스는 에러가 발생하지 않는다. 왜냐하면 HttpGet 클래스를 이용한 GET 메소드로 요청하는 것이기 때문이다.
따라서 별도의 Content-Length를 명시하지 않아도 된다.

그런데, 만약 POST 메소드로 요청시에는 Http body 가 첨부됨으로 Content-Length 를 http header 에 명시해 준다. 안드로이드 상에서는 다음과 같이 해 주면 된다.

method.setHeader("Content-Length", "" + httpBody.length);

여기서 이 코딩이 화근이다. 실제로 안드로이드 버전이 아닌 자바 버전의 아파치 HttpComponents를 이용할 경우에는 POST로의 요청일 경우에도 위의 코드를 넣어줄 경우에는 에러가 발생하지 않는다.
하지만, 안드로이드 애플리케이션에서 다음과 같이 http body 를 넣어줄 수 있는데, 여기서 위의 코드와 같이 Content-Length 를 명시할 경우 ClientProtocolException 이 발생한다.

byte[] httpBody = "Android http body".getByte();
HttpEntity entity = new ByteArrayEntity(httpBody);

HttpGet method = new HttpGet("http://test.wiseant.net/debugger");
method.setHeader("Content-Length", "" + httpBody.length);


05-22 06:40:56.533: WARN/System.err(1030): org.apache.http.client.ClientProtocolException

따라서 실제코드 상에서는 Content-Length 를 명시하는 setHeader 메소드를 사용하지 않아야 한다.
자바 버전의 HttpComponents 를 사용하는 것과 안드로이드의 Http client 컴포넌트를 사용하는 것은 상당 부분 차이가 난다.
흠... 이 버그 찾는데 오후 내도록 찾은 것이니 아깝진 하다... 쩝...^^;;

Posted by korcslewis
'앱 스토어' 시장은 애플 앱 스토어를 시작으로 현재 대부분의 스마트폰, 모바일 디바이스 영역에서는 당연히 되어가고 있다.
하긴 애플 앱 스토어의 기가 막힌 선순환 구조의 수익성을 경쟁회사들이 그냥 두고 있을리는 없다.

그리고 오늘 특이한 기사 하나를 접하게 되었다.
바로 전세계에서 가장 많은 개발자를 확보하고 있는 프로그래밍 언어 - 자바 - 바로 이 '자바 앱 스토어'를 자바를 창시한 회사인 Sun Microsystems 에서 오픈한다고 한다.

흠... 단연 앱 스토어 시장은 소프트웨어 시장에서의 새로운 생태계를 이루고 있다.
그리고 썬 마이크로시스템즈의 앱 스토어 시장으로의 진출은 가장 많은 개발자를 확보하고 있다는 강한 매력을 지니고 있기도 하다.
하지만, 자바를 기반으로 하는 대부분의 시장은 엔터프라이즈 또는 모바일 환경이다.
썬 마이크로서시스템즈가 어느 영역에 중점을 두는 건지는 정확히 모르지만 아마도 모바일 환경일 터... 그리고 최근엔 JavaFX 를 통한 RIA 시장도 크게 보고 있을 것이다.
이제 개발자와 사용자들이 자바를 선택할 것인가?

'자바 앱 스토어'가 오픈되고 성공여부를 지켜보는 것도 하나의 재미가 될 듯 하다.
그리고 내가 나아갈 방향도 역시 재미있어 질 거 같다.


Posted by korcslewis
2009/05/14 14:57

from String to InpuStream Java SE2009/05/14 14:57

부제 : 자바 문자열로부터 InputStream 얻어오기

String text = "자바";
InputStream inputStream = new ByteArrayInputStream(text.getBytes());

또는

InputStream inputStream = new ByteArrayInputStream(text.getBytes("utf-8"));

text.getBytes() 인자로는 Charset, CharsetName(String) 을 넣어 적절한 형태로 사용가능.


[참고]
이렇게 간단하지만 검색의 내용이 된다.


Posted by korcslewis
자바 IO를 이용한 FileReader 예제 소스이다. 파일이 .txt 파일이면 정상적으로 파일의 내용을 한 줄씩 읽어들여 화면에 디스플레이해 준다(사실은 표준출력한다).

import java.io.*;

public class FileReader {
    public static void main (String[] args) {
        System.out.println ("Program to demonstrate reading from a file");
        
        BufferedReader br = null;
        String fileName = args[0];
        
        // If an error occurs, go to the "catch" block
        try {
            // FileInputStream fis = new FileInputStream (fileName);
            FileReader fis = new FileReader (fileName);
            br = new BufferedReader (fis);
        
            // continue to read lines while there are still some left to read
            while ( br.ready() ) {
                System.out.println (br.readLine());
            }
        
            // Close the input stream
            br.close();
        } catch (Exception e) {
            // Handle any error in opening the file
            System.err.println("File input error");
        }
    } // End of main method
    
} // End of the class FileReader
Posted by korcslewis
JavaMail API를 이용하여 메일을 발송하는 예제의 대부분은 SMTP 서버를 통해서 단순하게 메일을 보내는 것이다.
하지만 사내에서 SMTP를 사용하여 메일을 전송하거나, 별도의 서비스를 위해서 SMTP 서버를 사용하는 경우에는 SMTP 서버에 계정을 이용하여 발송하기 때문에 계정에 대한 패스워드가 존재한다. 또한 SMTP 서버를 패스워드 없이 오픈해 놓으면 스팸 메일을 발송하는 원인이 될 수 있다.

그래서 SMTP 서버로 메일을 발송할 때 보안설정이 되어 있는 형태로의 자바메일 발송예제가 필요한 것이다.
다음 두 개의 소스 코드가 존재한다.


[MyAuthenticator.java]
package net.wiseant.mail;

import javax.mail.Authenticator;

/**
 * @author SangHyup LEE
 *
 */
public class MyAuthenticator extends Authenticator {

    private String id;
    private String pw;

    public MyAuthenticator(String id, String pw) {
        this.id = id;
        this.pw = pw;
    }

    protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
        return new javax.mail.PasswordAuthentication(id, pw);
    }

}

소스 코드에서 보는 바와 같이 java mail API의 Authenticator 클래스를 extends 하여 구현한 예제이다. 간략하게 생성자의 인자로 id와 password를 받는다. 그러면 해당 서버의 아이디와 패스워드로 인증된 객체를 생성하는 것이다.

[SMTPTest.java]
/**
 * 
 */
package net.wiseant.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author SangHyup LEE
 *
 */
public class SMTPTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String host = "mail.wiseant.net";//smtp 서버
        String subject = "메일제목";
        String content = "메일내용";
        String from = "wiseant@wiseant.net"; //보내는 사람
        String to = "korcslewis@gmail.com";
        
        try{
            // 프로퍼티 값 인스턴스 생성과 기본세션(SMTP 서버 호스트 지정)
            Properties props = new Properties();
            
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            
            MyAuthenticator auth = new MyAuthenticator("wiseant@wiseant.net", "password");
            
            Session mailSession = Session.getDefaultInstance(props, auth);
            // sess.getPasswordAuthentication(host);
            
            Message msg = new MimeMessage(mailSession);
            msg.setFrom(new InternetAddress(from));//보내는 사람 설정
            InternetAddress[] address = {new InternetAddress(to)};
            
            msg.setRecipients(Message.RecipientType.TO, address);//받는 사람설정
            
            msg.setSubject(subject);// 제목 설정
            msg.setSentDate(new java.util.Date());// 보내는 날짜 설정
            msg.setContent(content,"text/html;charset=euc-kr"); // 내영 설정 (HTML 형식)
            
            Transport.send(msg); // 메일 보내기
            
            System.out.println("메일 발송을 완료하였습니다.");
        } catch ( MessagingException ex ) {
            System.out.println("mail send error : " + ex.getMessage());
        } catch ( Exception e ) {
            System.out.println("error : " + e.getMessage());
        }
    }

}


SMTPTest.java 코드는 SMTP 서버의 인증후, 실제 메일을 발송하는 예제이다. Java Mail API를 사용하여 보내는 예제와 거의 동일하다. 다만 MyAuthenticator 클래스의 인스턴스를 생성하여 보내고자 하는 SMTP 서버로부터 보안 설정을 확인 후, 수행하는 것이 다를 뿐이다.
Posted by korcslewis
설명은 소스 주석에 포함하고 있다. 디버깅을 위해서 간단한 메시지도 출력하고 있다.


/**
 * n개의 방으로 구성된 1차원 배열에 값이 정렬되어 있을 때 임의의 값 x를 검색하는
 * binary search 알고리즘을 재귀적 함수로 구현한다.
 */
package net.wiseant.test.algorithm.search;
/**
 * @author Sang-Hyup Lee
 * @version 1.0
 *
 */
public class BinarySearchRecursive {

 static int arraySize = 1000;
 static int array[] = new int[arraySize];
 static int loopCount = 1;
 
 static void init() {
  for ( int i=0; i < arraySize; i++ ) {
   array[i] = i;
  }
 }
 
 static void binarySearch(int findNumber, int left, int right) {
  System.out.print("Loop count[" + loopCount + "], ");
  loopCount++;
  
  System.out.print("left : " + left + ", right : " + right + ", ");
  
  int center = (left + right) / 2;
  System.out.println("center : " + center);
  
  if ( array[center] == findNumber ) {
   System.out.println("Found it " + center + ", array[" + center + "]");
  } else if ( array[center] > findNumber ) {
   binarySearch(findNumber, left, center - 1);
  } else if ( array[center] < findNumber ) {
   binarySearch(findNumber, center + 1, right);
  }
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  init();
  
  int findNumber = 629;
  binarySearch(findNumber, 0, 999);
 }

}
Posted by korcslewis
언젠가 필요할지도 모를거 같아서 모아둔 자료이다.

자바 프로그램으로 원도우 레지스트리 다루기


Posted by korcslewis
문자열의 오브젝트의 길이는?
문자열 오브젝트 비교법
 
 
특히, "문자열 오브젝트 비교법"에 대한 글은 꼭 읽어보면 좋다.
다른 질문으로 기억하면 좋겠다...
 
'=='과 'equals'의 차이점은?
 
'=='는 두 개의 변수가 동일한 메모리를 참조하고 있는지를 비교한다.
'equals' 메소드는 두 개의 변수의 실제 char를 비교한다.

[이전 링크]
Posted by korcslewis