List<String> list = new ArrayList<>(); 

Iterator<String> iterator = list.iterator(); // while (iterator.hasNext()) { 
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { 
String string = iterator.next(); 
if (string.isEmpty()) { 
// Remove the current element from the iterator and the list. 
iterator.remove(); } 
}


'자바 > 자바팁' 카테고리의 다른 글

java로 implode 구현하기  (1) 2015.02.28
서버에 JNDI 설정 세팅하기  (0) 2015.01.03
[펌]Java 예제 - Queue(큐) Class  (0) 2014.12.01
레퍼런스까지 같이 복사하는 Clone 함수 사용법  (0) 2013.06.27
svn 관련 팁  (0) 2012.04.05
public static String implode(String separator, String... data) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < data.length - 1; i++) {
    //data.length - 1 => to not add separator at the end
        if (!data[i].matches(" *")) {//empty string are ""; " "; "  "; and so on
            sb.append(data[i]);
            sb.append(separator);
        }
    }
    sb.append(data[data.length - 1].trim());
    return sb.toString();
}

You can use it like

System.out.println(implode(", ", "ab", " ", "abs"));

or

System.out.println(implode(", ", new String[] { "ab", " ", "abs" }));


'자바 > 자바팁' 카테고리의 다른 글

java list 안전하게 제거  (0) 2017.02.10
서버에 JNDI 설정 세팅하기  (0) 2015.01.03
[펌]Java 예제 - Queue(큐) Class  (0) 2014.12.01
레퍼런스까지 같이 복사하는 Clone 함수 사용법  (0) 2013.06.27
svn 관련 팁  (0) 2012.04.05

로컬에서 할 땐 정말 쉽게 잘 됐는데 서버에 올릴땐 종나 안되서 삽질 이빠이 하고 내용 적어놓는다.


JSP 단독 톰캣 호스팅 하는 분들은 아래와 같이 하면 대충 다 맞을것이다.


서버 셋팅시 JNDI 설정방법 (CAFE24)


* 예제에 사용된 jdbc/mytc5의 mytc5 는 고객님 계정명과 같은 것으로 임의 변경하셔도 됩니다.

 

[server.xml]
tomcat/conf/server.xml에서 주석된 설정을 다음과 같이 변경합니다. (중요) 하단에 Context 태그 사이에 꼭 넣어야 작동함

<Resource name="jdbc/mytc5"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/dbname"
username="dbuser"
password="dbpasswd"
maxActive="20"
maxIdle="10"
maxWait="3000"/>

 

 

[web.xml]

WEB-INF/web.xml에서 다음을 추가합니다.

 

<resource-ref>
<res-ref-name>jdbc/mytc5</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

 

 

* Tomcat 호스팅의 tomcat 7 이용 시 추가사항

[context.xml]

tomcat/conf/context.xml에 <Context></Context> 사이에 다음을 추가합니다.

 

<ResourceLink type="javax.sql.DataSource"
                      name="jdbc/mytc5"
                      global="jdbc/mytc5j" />

 


[jdbctest.jsp]


<html>
<head>
<%@ page errorPage="errorpg.jsp" 
import="java.sql.*, 
javax.sql.*, 
java.io.*,
javax.naming.InitialContext,
javax.naming.Context" %>
</head>
<body>
<h1>JDBC JNDI Resource Test</h1>

<%
InitialContext initCtx = new InitialContext();
DataSource ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/mytc5");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select version();");
while (rset.next()) { 
out.println("mysql version=="+rset.getString("version()")); 
}
rset.close();
stmt.close();
conn.close();
initCtx.close();
%>
</body>
</html>

'자바 > 자바팁' 카테고리의 다른 글

java list 안전하게 제거  (0) 2017.02.10
java로 implode 구현하기  (1) 2015.02.28
[펌]Java 예제 - Queue(큐) Class  (0) 2014.12.01
레퍼런스까지 같이 복사하는 Clone 함수 사용법  (0) 2013.06.27
svn 관련 팁  (0) 2012.04.05

출처 : http://qortn.tistory.com/225


Java 예제 - Queue(큐) Class 

지난번엔 Stack(스택) 클레스에 대해 알아봤습니다. 이번엔 Stack class 와는 반대 개념인 Queue(큐) 클래스에 대해 알아보겠습니당!!





위의 그림에서 보듯이 요소를 데어티 구조의 양쪽 단에서만 저장 / 접근 할수 있는 컬렉션 입니다. 

FIFO ( First - In - First - Out ) 구조로 위아래 양쪽 구멍이 뚫려 있어 쉽게 말해 "밑 빠진 독" 이라고 볼수 있습니다(물론 줄줄 새진 않죠 ^^;;)

이렇게 들어오는곳과 나오는곳이 다르기 때문에 Queue(큐)에 먼저 들어간 데이터가 가장 먼저 나오게 됩니다^^

Queue(큐) 클래스 인스턴스를 생성하기 위해선 아래와 같이 "LinkedList()" 생성자를 호출해 주면됩니다


Queue Myque = new LinkedList();



Queue(큐) 클래스의 접근 메서드는 크게 "offer()" 와 "poll()" 메서드가 가장 중요한 역활을 합니다. Stack 클래스와 마찬가지로 "peek()" 메서드도 있다

는 사실도 잊지 말아주세요 !! ^^


메서드설명
boolean offer()Queue(큐)에 객체를 넣는다
poll()Queue(큐)에서 데이터를 꺼내온다. 만일 Queue(큐)가 비어있다면 null 을 반환.
peek()큐의 맨 아래 있는 객체를 반환한다. 이 때 객체를 큐에서 제거하진 않는다.




자 이제 Queue(큐) 를 이용한 예제를 한번 해보도록 하겠습니당!!


import java.util.*;

public class ExQueue {
 
 public static void main(String[] args)
 {
  Queue Myque = new LinkedList(); 
  
  String str1 = "1. 머루";
  String str2 = "2. 별머루";
  String str3 = "3. 산머루";
  String str4 = "4. 달머루";
  
  Myque.offer(str1); 
  Myque.offer(str2);
  Myque.offer(str3);
  Myque.offer(str4);
  
  while(Myque.peek() != null) 
  {
   String val = (String)Myque.poll(); 
   System.out.println("값은 " + val);
  }
  
 }

}


타이핑 하기 귀찮으신분들을 위한 -_-;; (길지 않으니 타이핑 해보는걸 추천 !!^^;;)


소스파일 입니다.(주석도 있습니다 !! ^^;;




휴 .. 그럼 실제 구동화면을 한번 볼까요??




위 이미지를 보시면 처음 입력된 "머루" ~ "달머루" 까지 입력한 순서대로 출력이 되는걸 확인할수 있습니다.

지금까지 Stack 과 Queue 이 두개의 클래스에 대해 알아봤는데요 ~ 

솔직한 말로 .. 이 두개의 클래스는 거의 사용되지 않습니다 -ㅅ-;; 

그렇다고 모르고 넘어가서도 안되는 뭐 그런 클래스에요 !!! 

다음엔 Vector 클래스 구조 에 대해 설명할껀데요. 요놈 때문에 Stack 과 Queue 를 알아둬야 한다는점 !!

Vector 클래스는 난이도가 살짝? 있어용 !! 

'자바 > 자바팁' 카테고리의 다른 글

java로 implode 구현하기  (1) 2015.02.28
서버에 JNDI 설정 세팅하기  (0) 2015.01.03
레퍼런스까지 같이 복사하는 Clone 함수 사용법  (0) 2013.06.27
svn 관련 팁  (0) 2012.04.05
NIO 간단한 파일읽기 예제  (0) 2012.01.19


public class CloneMainCls {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try {
   MyNumbers mn = new MyNumbers();
   MyNumbers mn2 = (MyNumbers) mn.clone();
   
   mn2.getNumbers()[1] = 3;
   
   System.out.println(mn.getNumbers()[1] + ":" + mn2.getNumbers()[1]);
   
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }

}

class MyNumbers implements Cloneable{
 private int[] numbers = null;
 
 MyNumbers(){
  numbers = new int[]{0,1,2,3,4,5,6,7,8,9};
 }
 @Override
 protected Object clone() throws CloneNotSupportedException {
  MyNumbers numbers2 = (MyNumbers)super.clone();
  numbers2.numbers = (int[]) numbers.clone();
  
  return numbers2;
 }
 
 public int[] getNumbers() {
  return numbers;
 }
}

'자바 > 자바팁' 카테고리의 다른 글

서버에 JNDI 설정 세팅하기  (0) 2015.01.03
[펌]Java 예제 - Queue(큐) Class  (0) 2014.12.01
svn 관련 팁  (0) 2012.04.05
NIO 간단한 파일읽기 예제  (0) 2012.01.19
NIO가 무엇일까요?  (1) 2012.01.18

일단 svn 저장소는 최신 소스를 유지하는 trunk가 있고 trunk에서 분리되어 나온 branch라는 것이 있습니다

이름만 다를 뿐 실제로는 각각 하나의 디렉토리라고 보셔도 됩니다.

개발 팀마다 svn저장소를 사용하는 방법이 조금씩 다르기 때문에

어떻게 사용하는 것이 맞다고 말씀드리긴 힘듭니다.

 

제가 사용하는 방법을 예를 들어보겠습니다.

HelloWorld라는 프로젝트를 SVN저장소에 생성합니다.

그리고 프로젝트의 소스들을 trunk에 저장합니다.

해당 프로젝트에 A라는 기능을 추가하기로 결정되었습니다.

그러면 trunk에 있는 최신 소스를 그대로 복사하여 A라는 branch를 생성합니다.

이 시점에서 trunk와 A branch는 동일합니다.

이제 A에 있는 소스들을 여러사람이 함께 수정합니다.

기능 추가가 완료되면 A에서 변경된 소스들을 trunk와 병합합니다.

이것을 merge라고 합니다. 

 

그러면 trunk는 다시 A기능이 추가된 최신소스가 됩니다.

이제 다시 HelloWorld프로젝트에 B라는 기능을 추가해야 합니다.

그러면 또 trunk의 소스를 그대로 복사하여 B라는 branch를 생성합니다.

그리고 B branch에 기능을 추가하고 완료되면 B기능에서 변경된 소스를 trunk로 merge합니다.

 

이것이 계속 반복되면서 trunk는 항상 최신소스로 유지가 됩니다.

SVN의 진정한 기능은 두 개 이상의 기능추가가 동시에 진행되어야 할 때 발휘됩니다.

즉 A, B라는 두 개의 기능을 추가해야 하는데 두 개의 작업이

서로 다른 팀에 의해서 동시에 진행된다고 가정합니다.

 

그러면 branch를 하나 생성해서 서로 같은 소스를 수정하다보면 버그가 발생해도

이게 A기능때문에 생긴 버그인지 B기능때문에 생긴 버그인지 알기가 힘들고 유지보수도 힘들어집니다.

그래서 trunk에서 branch를 두 개 생성하여 각각 따로 기능 추가를 합니다.

그리고 각각 작업이 완료되면 변경된 부분만 trunk로 merge합니다.

이렇게 되면 여러개의 작업이 동시에 진행되도 각각 서로 분리된 소스로 작업을 할 수 있게 됩니다.

 

일단 위 내용이 SVN의 대략적인 개념입니다.

 

이제 질문자님께서 질문하신 것에 대하여 이야기해보겠습니다.

파일을 수정하여 변경사항을 SVN 저장소에 반영하는 것을 commit 한다고 합니다.

 

최초에 프로젝트의 trunk를 checkout받아서 파일을 수정하다 보면 다른 사람이 해당 파일을 수정하여

commit하는 경우가 매우 자주 발생합니다.

commit은 소스 전체가 되는 것이 아니라 변경된 부분만 되는 것이기 때문에

질문자님은 update라는 명령을 사용하시면 변경된 부분만 최신 소스로 업데이트하실 수 있습니다.

매번 새로 checkout받으실 필요가 없다는 말입니다.

그런데 이때 같은 부분을 고치고 있었다면 conflict, 즉 충돌이 발생하게 됩니다.

충돌이 발생하면 해당 부분을 적절히 수정하여 충돌을 해제할 수 있습니다.

 

대략적인 감이 잡히셨는지 모르겠네요.

svn에 관한 검색을 하셔서 잘 정리된 페이지를 쭉 한 번 읽어보시길 추천드립니다

 

'자바 > 자바팁' 카테고리의 다른 글

[펌]Java 예제 - Queue(큐) Class  (0) 2014.12.01
레퍼런스까지 같이 복사하는 Clone 함수 사용법  (0) 2013.06.27
NIO 간단한 파일읽기 예제  (0) 2012.01.19
NIO가 무엇일까요?  (1) 2012.01.18
자바 NIO 강좌  (0) 2012.01.18

출처 : 
http://devhome.tistory.com/10 
FileChannel은 
java.nio.channels.FileChannel 에 존재하는 새로운 io 패키지중의 하나이다.

파일 접근적인 속도면에서는 java.io 에서 제공하는 다른 패키지에 비해 성능이 우수하다.

아직은 많이 보편적으로 사용하는 패키지가 아니어 많은 자료를 구하지 못해 간단한 파일을 읽는 방법을 소개한다.


[ 파일읽기 예제소스 ]
01.import java.io.File;
02.import java.io.FileInputStream;
03.import java.io.IOException;
04.import java.nio.ByteBuffer;
05.import java.nio.channels.FileChannel;
06. 
07.public class ObjectTest
08.{
09.public static void main(String args[])
10.{
11.File            inFile   = null;
12.FileInputStream inStream = null;
13.FileChannel     inChannel= null;
14.ByteBuffer      bBuffer  = null;
15.String[]        strBuffer= null;
16. 
17.try
18.{
19.// Open File Channel
20.inFile   = new File("test.txt");
21.inStream = new FileInputStream(inFile);
22.inChannel= inStream.getChannel();
23. 
24.// buffer init...
25.bBuffer = ByteBuffer.allocate((int)inChannel.size());
26.// ANSI & UTF-16 : inChannel.read(bBuffer);
27.// UTF-8         : inChannel.read(bBuffer, 3);
28.inChannel.read(bBuffer);
29. 
30.// casting : ByteBuffer -> String
31.// ANSI   : strBuffer = new String(((ByteBuffer)bBuffer.flip()).array()).split("\r\n");
32.// UTF-8  : strBuffer = new String(((ByteBuffer)bBuffer.flip()).array(), "UTF-8").split("\r\n");
33.// UTF-16 : strBuffer = new String(((ByteBuffer)bBuffer.flip()).array(), "UTF-16").split("\r\n");
34.strBuffer = newString(((ByteBuffer)bBuffer.flip()).array()).split("\r\n");
35. 
36.// print read data from file
37.forint i = 0; i < strBuffer.length; i++ )
38.System.out.println(strBuffer[i]);
39.}
40.catch(IOException e)
41.{
42.e.printStackTrace();
43.return;
44.}
45.finally
46.{
47.try
48.{
49.if( inStream != null )
50.inStream.close();
51.if( inChannel != null )
52.inChannel.close();
53.}
54.catch(IOException e)
55.{
56.e.printStackTrace();
57.return;
58.}
59.}
60.}
61.}

위의 프로그램 소스는 현재 대용량의 파일의 경우는 사용해서는 안돼는 코드이다. 한번에 파일의 전 데이터를
 
읽어오도록 되어 있기때문이다. 그리고 ByteBuffer의 초기화 사이즈는 int형이고 FileChannel의 사이즈는 long형

을 사용하고 있기 때문에 문제가 발생한다.

'자바 > 자바팁' 카테고리의 다른 글

레퍼런스까지 같이 복사하는 Clone 함수 사용법  (0) 2013.06.27
svn 관련 팁  (0) 2012.04.05
NIO가 무엇일까요?  (1) 2012.01.18
자바 NIO 강좌  (0) 2012.01.18
[자바팁]SequenceInputStream example  (1) 2012.01.11

NIO가 무엇일까요?  
NonBloking Input-Output 입니다. 기존의 일반 IO는 항상 블럭화가 되면서, 처리를 해왓습니다.
블럭화가되면 그블럭이 풀리기전까진 아무것도  수행할수 없지요. 그래서 그것이 큰 단점이기도 하지요.
NIO는 JDK 1.4 이전에는 존재 하지 않는 방법론입니다. 그 이후에 생긴 방법론이므로 참고 하시면 되구요.
어쨋든 그래서 NIO가 무엇이냐면.. 블럭화(잠수)를 타지않고 작업을 할수있게 해주는 방법론이에요.
서버가 존재하고 통신을 할때 메인스레드가 블럭화(잠수)를 타버리면 그 블럭화가 풀리기전까진 아무것도 못하잖아요..?
이것은 블럭을 시키지않고서, 누가 들어오던지 자료를 요청하던지 블럭 시키지않고 그냥 무작정 일만 처리시키는것이죠.

하나  이상적인 를 들어볼가요?

사장 : 어이 신입.. 내일까지 3천장 A4용지 복사좀 해놓게나...
신입 : 예!!

1시간후...

부장 : 어이 신입.. 미안한데말이야... 프로그래밍 유지보수가 생겨버렷어... 저 코드좀 내일까지 고쳐주게나...
신입 :  네 -_-;

과장 : 이보게나..  가족사진이 있는데 그지가치 나왓어 좀 고쳐준나..
신입 : 네 ㅜㅜ

위에서 신입이라는 사람이 있지요.. 지금 3가지 일을 부여 받았어요.
지금 신입이 해야되는일은  (전화받기,  복사하기,  코딩하기) 입니다.

이제 위의 상황을 IO와 NIO로 어떻게 처리할수있는지 비교해보겠씁니다.

1.  I/O 를 이용한 일처리
- 사장이 시킨 3천장 복사를 다한다. 그거다하기전까진 다 쌩간다.
- 그담에 부장이 시킨 코딩을 한다...
- 마지막 과장이 시킨 사진 작업을한다.

2. N/I/O를 이용한 일처리
- 복사기를 돌려놓고, 코딩두 하면서, 포토샵을 켜서 사진작업을합니다

무조건 다할대까지 하는것이 아니라..  계속 요청 들어오는데로 돌아가면서  하는것입니다.

NIO에서 추가적으로 생긴 개념은 Channel이라는 것과 Selector라는것이 있습니다.
채널은 스트림과같이 연결된 것들 끼리  읽기 쓰기 동시에 이루어질수록 하게 해주는것입니다.
일반IO는 입력용, 출력용 따로있었지요~
그리고 Selector는 c에서의 select와 비슷한거지만  모든 연결을 중앙집중식으로 관리해주는것 입니다.
즉, 이 Selector만 스레드로 생겨나고 블로킹되어 모든 클라이언트의 연결을 책임지고 관리해 줍니다.

만약, 클라가 서버와 자료를 전송하기 위해 특정 포트와 통신한다면 이 Selector가 이를 감시하여
이벤트 발생한 IO와 관련된 채널을 불러와서 작업을 수행하는 방법입니다.
누군가 요청을 하게되면  CONNECT인지 READ인지 WRITE인지 구분을 할수있습니다.

결론 아무리 많은 클라이언트가 접속을 해도  Selector 를 담당하는부분만 쓰레드 한개로 처리시키면 백점입니다. ㅋ
이정도면 개념을 어느정도 잡을수 있을겁니다.  이보다 개념적으로 더 자세히 알고싶으시다면... 
이곳을 참고하세요. -> http://www.javacafe.or.kr/lecture/cafeLecture/network/nio/microsoft1_SJH.html 

이제 간단한 채팅에코 서버를 구현해볼까요..?

NIO 서버
package com.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Vector;

public class NioServer {
    private Selector selector = null;
    private ServerSocketChannel serverSocketChannel = null;
    private ServerSocket serverSocket = null;

    private Vector room = new Vector();

    public void initServer() {
        try {
            selector = Selector.open();

            // Create ServerSocket Channel
            serverSocketChannel = ServerSocketChannel.open();

            // 비 블록킹 모드로 설정한다.
            serverSocketChannel.configureBlocking(false);

            // 서버소켓 채널과 연결된 서버소켓을 가져��다.
            serverSocket = serverSocketChannel.socket();

            // 주어진 파라미터에 해당��는 주소다. 포트로 서버소켓을 바인드한다.
            InetSocketAddress isa = new InetSocketAddress("localhost", 9999);
            serverSocket.bind(isa);

            // 서버소켓 채널을 셀렉터에 등록한다.
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void startServer() {
        System.out.println("Server is Started....");
        try {
            while (true) {
                selector.select(); // 셀렉터�� select() 메소드로 준비된 이벤트가 있는지 확인한다.

                Iterator it = selector.selectedKeys().iterator();

                while (it.hasNext()) {
                    SelectionKey key = (SelectionKey) it.next();

                    if (key.isAcceptable()) {
                        accept(key);
                    } else if (key.isReadable()) {
                        read(key);
                    }
                    it.remove();
                } // end of while(iterator)
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void accept(SelectionKey key) {
        ServerSocketChannel server = (ServerSocketChannel) key.channel();

        try {
            // 서버소켓 채널�� accept() 메소드로 서버소켓을 생성한다.
            SocketChannel sc = server.accept();
            // 생성된 소켓채널을 비 블록킹과 읽기 모드로 셀렉터에 등록한다.

            if (sc == null)
                return;

            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_READ);

            room.add(sc); // 접속자 추가
            System.out.println(sc.toString() + "클라이언트가 접속했습니다.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void read(SelectionKey key) {

        // SelectionKey로부터 소켓채널을 얻어��다.
        SocketChannel sc = (SocketChannel) key.channel();
        // ByteBuffer를 생성한다.
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

        try {
            // 요청한 클라이언트�� 소켓채널로부터 데이터를 읽어들인다.
            int read = sc.read(buffer);
        } catch (IOException ex) {
            try {
                sc.close();
            } catch (IOException e) {
            }

            room.remove(sc);
            ex.printStackTrace();
        }

        try {
            broadcast(buffer);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        if (buffer != null) {
            buffer.clear();
            buffer = null;
        }
    }

    private void broadcast(ByteBuffer buffer) throws IOException {
        buffer.flip();
        Iterator iter = room.iterator();
        while (iter.hasNext())
        {
            SocketChannel sc = (SocketChannel) iter.next();

            if (sc != null) {
                sc.write(buffer);
                buffer.rewind();
            }
        }
    }
}

NIO 기반 클라이언트
package com.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import java.util.Scanner;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NioClient {
    static Selector selector = null;
    private SocketChannel sc = null;

    public void initServer() {
        try {
            selector = Selector.open();
            sc = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999));
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_READ);
        } catch (IOException ex) {
        }
    }

    public void startServer() {
        initServer();
        Receive rt = new Receive();
        new Thread(rt).start();
        startWriter();
    }

    public void startWriter() {
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        try {
            while (true)
            {
                Scanner scanner = new Scanner(System.in);
                String message = scanner.next();
                buffer.clear();
                buffer.put(message.getBytes());
                buffer.flip();
                sc.write(buffer);
            }
        } catch (Exception ex) {
        } finally {
            clearBuffer(buffer);
        }
    }

    static void clearBuffer(ByteBuffer buffer) {
        if (buffer != null) {
            buffer.clear();
            buffer = null;
        }
    }
}

class Receive implements Runnable {
    private Charset charset = null;
    private CharsetDecoder decoder = null;

    public void run() {
        charset = Charset.forName("EUC-KR");
        decoder = charset.newDecoder();
        try {
            while (true)
            {
                NioClient.selector.select();
                Iterator it = NioClient.selector.selectedKeys().iterator();
               
                while (it.hasNext())
                {
                    SelectionKey key = (SelectionKey) it.next();
                    if(key.isReadable()) {
                        read(key);
                    }else{}
                    it.remove();
                }
            }
        } catch (Exception ex) {}
    }

    private void read(SelectionKey key) {
        SocketChannel sc = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        int nbyte=0;
        try {
            nbyte = sc.read(buffer);
            buffer.flip();
            String data = decoder.decode(buffer).toString();
            System.out.println("Receive Message - " + data);
            NioClient.clearBuffer(buffer);
        }catch (IOException ex){
            try {
                sc.close();
            } catch (IOException ex1) {
            }
        }
    }
}

'자바 > 자바팁' 카테고리의 다른 글

svn 관련 팁  (0) 2012.04.05
NIO 간단한 파일읽기 예제  (0) 2012.01.19
자바 NIO 강좌  (0) 2012.01.18
[자바팁]SequenceInputStream example  (1) 2012.01.11
자바 압축 관련 정보  (0) 2012.01.10

출처 : http://blog.naver.com/skyadult?Redirect=Log&logNo=20025986907

 

14. ServerSocketChannel 클래스와 SocketChannel 클래스
이제 실전에 들어가기 전에 ServerSocketChannel 클래스와 SocketChannel 클래스에 대해 먼저 알아보자. 이들은 net패키지의 ServerSocket클래스와 Socket클래스를 채널로서 다루고자 할 때 쓰는 SelectableChannel이다. 이들 네트워크 관련 채널들은 독자적으로 소켓의 역할을 대처하지는 않는다. 대신 소켓 클래스를 내부에 가지고 있으면서 이들의 기능을 채널화하는데 적절히 이용하게 된다.
 
1> ServerSocketChannel 클래스
① ServerSocketChannel 클래스 생성
ServerSocketChannel을 얻으려면 open()메서드를 사용한다. 단 이때 얻는 채널은 내부의 소켓이 아직 bind되지 않은 상태이기 때문에 적절한 IP주소와 포트 번호로 binding시켜줘야 한다. 일반적으로 다음과 같은 순서로 채널을 얻고 binding 한다.
1. ServerSocketChannel 얻기.
ServerSocketChannel server=ServerSocketChannel.open();
2. 내부 소켓을 얻는다.
ServerSocket socket=server.socket();
3. binding 한다.
SocketAddress addr=new InetSocketAddress(포트번호);
socket.bind(addr);
② ServerSocketChannel 클래스 주요 메서드
ㅁ public abstract SocketChannel accept() : 이 채널의 소켓에 대한 접속을 받아들여 SocketChannel을 리턴한다. 이때 ServerSocketChannel이 Blocking I/O 모드라면 accept()는 Blocking되지만 Non-Blocking I/O 모드라면 Blocking되지 않는다. 따라서 당장 어떤 접속요구가 없다면 null을 리턴한다. 하지만 리턴된 SocketChannel은 ServerSocketChannel이 Blocking I/O 모드이든 아니든 상관없이 무조건 Blocking I/O 모드로 시작한다.
ㅁ public static ServerSocketChannel open() : ServerSocketChannel를 얻는다. 이때 리턴된 ServerSocketChannel는 아직 bind되지 않은 상태이므로 소켓의 bind 메소드를 사용해 특정의 주소에 binding을 해주어야 한다.
ㅁ public abstract ServerSocket socket() : 내부 소켓을 얻는다.
ㅁ public final int validOps() : 현재 채널이 할 수 있는 해당 동작(ops)을 리턴한다. 서버소켓채널은 SelectionKey.OP_ACCEPT 만 할 수 있다.
 
2> SocketChannel 클래스
① SocketChannel로 접속하기
소켓채널을 얻기 위해서는 open()메서드를 사용하면 되는데 open()에는 인자가 있는 것과 없는 것이 있다. 만약 인자 없이 open()를 사용한다면 접속이 되지 않는 소켓채널을 리턴하므로 connect()메서드를 이용해서 접속을 해주어야 한다. 인자로 SocketAddress 객체를 준다면 접속이 된 소켓채널을 얻을 수 있다. 두가지 경우를 다 보자.
* 접속된 소켓채널 얻기
SocketAddress addr=new InetSocketAddress("ip주소", 포트번호);
SocketChannel socket=SocketChannel.open(addr);
* connect() 사용해서 접속하기
SocketAddress addr=new InetSocketAddress("ip주소", 포트번호);
SocketChannel socket=SocketChannel.open();
socket.connect(addr);
* SocketChannel에서 Non-Blocking I/O 모드일 경우에는 open(SocketAddress addr)해도 되지만, open()해서 connect(SocketAddress addr)했을 경우에는 즉시 연결작업이 끝나지 않을 수 있어서 이 메서드가 false를 리턴하게 되므로, finishConnect()로 연결작업을 끊어줘야 한다. 만약 연결이 제대로 안되었다면 false가 리턴된다. Blocking I/O 모드일 때는 connect() 호출이 Blocking 되면 연결이 끊길때까지 지속된다.
 
② SocketChannel 클래스 주요 메서드
ㅁ public abstract boolean connect (SocketAddress remote) : 인자로 들어온 SocketAddress 객체 정보를 가지고 현재 채널에 소켓을 접속한다. 연결이 제대로 안되면 false를 리턴한다.
ㅁ public abstract boolean finishConnect () : 소켓채널의 접속 처리를 완료한다.
ㅁ public abstract boolean isConnected () : 채널소켓이 접속이 되었는지 유무를 리턴.
ㅁ public abstract boolean isConnectionPending () : 이 채널상에서 접속 조작이 진행중인지 어떤지를 판단. 즉 접속이 시작되고 완료하지 않은 경우, finishConnect()가 호출되고 있지 않는 경우 true를 리턴.
ㅁ public static SocketChannel open () : 접속되지 않는 소켓채널을 리턴.
ㅁ public static SocketChannel open (SocketAddress remote)
: 접속된 소켓채널을 리턴.
ㅁ read()류 메서드
ㅁ public abstract int read (ByteBuffer dst)
ㅁ public final long read (ByteBuffer [] dsts)
ㅁ public abstract long read (ByteBuffer [] dsts, int offset, int length)


ㅁ write()류 메서드
ㅁ public abstract int write (ByteBuffer src)
ㅁ public final long write (ByteBuffer [] srcs)
ㅁ public abstract long write (ByteBuffer [] srcs, int offset, int length)
 
3> 예제
간단한 채팅을 만들어보자. 단순하게 서버에 클라이언트가 접속, 메세지를 보내면 서버가 메세지를 읽어 출력하고 서버도 메세지를 보내는 소스이다. 우선 순서를 보자.
<< 서버측 >>
  1. 채널들을 관리할 Selector를 얻는다.
    Selector selector=Selector.open();
  2. ServerSocketChannel를 얻는다.
    ServerSocketChannel server=ServerSocketChannel.open();
  3. 내부 소켓을 얻는다.
    ServerSocket socket=server.socket();
  4. binding 한다.
    SocketAddress addr=new InetSocketAddress(포트번호);
    socket.bind(addr);
  5. ServerSocketChannel을 Selector에 등록시킨다. ServerSocket는 OP_ACCEPT동작만 할 수 있다.
    server.register(selector, SelectionKey.OP_ACCEPT);
  6. 클라이언트의 접속을 대기한다. 이때 접속이 되면 accept()에 의해 상대방 소캣과 연결된 SocketChannel의 인스턴스를 얻는다. 이 채널는 읽기(OP_READ),쓰기(OP_WRITE),접속(OP_CONNECT) 행동을 지원한다.
    SocketChannel socketChannel=serverChannel.accept();
  7. 접속된 SocketChannel를 Selector에 등록한다.
    socketChannel.register(selector, 소켓채널의 해당행동);
  8. 채널이 취할 수 있는 3가지 동작(읽기(OP_READ),쓰기(OP_WRITE),접속(OP_CONNECT) )에 대해서 검사한다. 이때는 다음과 같은 메서드를 이용해서 체크를 한다.
    isConnectable() : true이면 상대방 소켓과 새로운 연결이 됐다는 뜻이다. 이때 Non-Blocking I/O 모드일 경우에는 연결과정이 끝나지 않는 상태에서 리턴될 수도 있다. 그러므로 SocketChannel 의 isConnectionPending()메서드가 true를 리턴하는지 아닌지를 보고 true를 리턴한다면 finishConnection()를 명시적으로 불러서 연결을 마무리짓도록 한다.
    isReadable() : true이면 읽기(OP_READ) 동작이 가능하다는 뜻으로 SocketChannel로부터 데이터를 읽는 것에 관한 정보를 받을 준비가 되었다는 뜻이다. 따라서 버퍼에 읽어들이기만 하면된다.
    isWritable() : true이면 쓰기(OP_WRITE) 동작이 가능하다는 뜻으로 SocketChannel에 데이터를 쓸 준비가 되었다는 뜻이다. 따라서 버퍼의 데이터를 이 채널에 write()하면 된다.
<< 클라이언트측 >>
  1. SocketChannel를 얻어서 접속한다.
    SocketAddress addr=new InetSocketAddress("localhost", 8080);
    SocketChannel socket=SocketChannel.open(addr);
  2. 버퍼를 만들고 서버에서 들어온 데이터를 읽고 쓰기를 한다.
자, 이제 소스를 보자. 먼저 서버측 소스인 serverSocketChannel .java를 보자.
serverSocketChannel.java
package nio;
import! java.io.IOException;
import! java.net.InetSocketAddress;
import! java.net.ServerSocket;
import! java.net.SocketAddress;
import! java.nio.ByteBuffer;
import! java.nio.channels.ClosedChannelException;
import! java.nio.channels.SelectableChannel;
import! java.nio.channels.SelectionKey;
import! java.nio.channels.Selector;
import! java.nio.channels.ServerSocketChannel;
import! java.nio.channels.SocketChannel;
import! java.util.Iterator;
public class serverSocketChannel implements Runnable {
    Selector selector;
    int port=8080;
   
    private void Log(Object obj) {
        System.out.println(obj.toString());
    }
   
    public serverSocketChannel()
    throws IOException {
        initServer();
        Log("****************************************");
        Log("클라이언트의 접속을 기다리고 있습니다");
        Log("****************************************");
    }
    private void initServer()
    throws IOException, ClosedChannelException {
        serverRegister(socketBind(selectorOpen()));
    }
    private void serverRegister(ServerSocketChannel server)
    throws IOException, ClosedChannelException {
        server.configureBlocking(false);
        int validOps = server.validOps();
        Log("ServerSocketChannel.validOps() : " + validOps);
        Log(", " + (validOps == SelectionKey.OP_ACCEPT));
        server.register(selector, SelectionKey.OP_ACCEPT);
    }
    private ServerSocketChannel socketBind(ServerSocketChannel server)
    throws IOException {
        ServerSocket socket = server.socket();
        SocketAddress addr = new InetSocketAddress(port);
        socket.bind(addr);
        Log(server);
        return server;
    }
    private ServerSocketChannel selectorOpen() throws IOException {
        selector = Selector.open();
        ServerSocketChannel server = ServerSocketChannel.open();
        Log(server);
        return server;
    }
    public void run() {
        int socketOps = SelectionKey.OP_CONNECT |
                        SelectionKey.OP_READ |
                        SelectionKey.OP_WRITE;
        while(true) {
            try {
                selector.select();
            } catch(IOException ioe) {
                ioe.printStackTrace();
            }
            keyIterator(selector.selectedKeys().iterator(), socketOps);
        }
    }
    private void keyIterator(Iterator iter, int socketOps) {
        while (iter.hasNext()) {
            try {
                SelectionKey selected = (SelectionKey)iter.next();
                iter.remove();
                SelectableChannel channel = selected.channel();
               
                if (channel instanceof ServerSocketChannel) {
                    ServerSocketChannel serverChannel = (ServerSocketChannel)channel;
                    SocketChannel socketChannel = serverChannel.accept();
                    if (socketChannel == null) {
                        Log(" # null server socket");
                        continue;
                    }
                    Log(" # socket accepted : " + socketChannel);
                    socketChannel.configureBlocking(false);
                    int validOps = socketChannel.validOps();
                    Log("SocketChannel.validOps() : " + validOps);
                    Log(", " + (validOps == socketOps));
                    socketChannel.register(selector, socketOps);
                }
                else {
                    SocketChannel socketChannel = (SocketChannel)channel;
                    if (selected.isConnectable())
                        isConnectable(socketChannel);
                    if (selected.isReadable())
                        isReadable(socketChannel);
                    if (selected.isWritable())
                        isWritable(socketChannel);
                }
            } catch(IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
    private void isWritable(SocketChannel socketChannel)
    throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(20);
        String s = "Hello Client!!";
        byte[] bytes = s.getBytes();
        buf.put(bytes);
        buf.clear();
        socketChannel.write(buf);
        System.out.println(" # socket write : " + s);
    }
    private void isReadable(SocketChannel socketChannel)
    throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(20);
        socketChannel.read(buf);
        buf.clear();
        Log("# socket read :");
        while (buf.hasRemaining()) {
            System.out.print((char)buf.get());
        }
    }
    private void isConnectable(SocketChannel socketChannel)
    throws IOException {
        Log(" # socket connected");
        if (socketChannel.isConnectionPending()) {
            Log(" # Connection is pending");
            socketChannel.finishConnect();
        }
    }
    public static void main(String[] args)
    throws IOException {
        new Thread(new serverSocketChannel()).start();
    }
}
clientSocketChannel.java -->클라이언트측
package nio;
import! java.io.IOException;
import! java.net.InetSocketAddress;
import! java.net.SocketAddress;
import! java.nio.ByteBuffer;
import! java.nio.channels.SocketChannel;

public class clientSocketChannel {
    private SocketChannel socket = null;
   
    public static void main(String[] args)
    throws Exception {
        clientSocketChannel client = new clientSocketChannel();
        client.exec();
    }
    public void exec()
    throws IOException {
        open();       
        while (true) {
            getMesage(socket);
            sendMessage(socket);
        }
    }
    private void open()
    throws IOException {
        SocketAddress addr = new InetSocketAddress("localhost", 8080);
        socket = SocketChannel.open(addr);
        System.out.println(socket);
        System.out.println("# isBlocking() : " + socket.isBlocking());
    }
    private void getMesage(SocketChannel socket) throws
    IOException {
        ByteBuffer buf = ByteBuffer.allocate(20);
        int read = 0;
        socket.read(buf);
        buf.clear();
        System.out.print("# socket read :");
        while (buf.hasRemaining()) {
            System.out.print((char)buf.get());
        }
        buf.clear();
    }
    private void sendMessage(SocketChannel socket)
    throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(20);
        String msg = "Hello Server!!";
        byte[] bytes = msg.getBytes();
        buf.put(bytes);
        buf.clear();
        socket.write(buf);
        System.out.println("n" + "# socket write : " + msg);
        buf.clear();
    }

'자바 > 자바팁' 카테고리의 다른 글

NIO 간단한 파일읽기 예제  (0) 2012.01.19
NIO가 무엇일까요?  (1) 2012.01.18
[자바팁]SequenceInputStream example  (1) 2012.01.11
자바 압축 관련 정보  (0) 2012.01.10
JSP 및 JAVA로 오직 POST 방식으로 받을때  (0) 2011.12.13
The SequenceInputStream class allows you to concatenate multiple InputStreams. The construction of aSequenceInputStream is different from any other InputStream. A SequenceInputStream constructor uses either a pair of InputStreams or an Enumeration of InputStreams as its argument:

SequenceInputStream(InputStream first, InputStream second
SequenceInputStream(Enumeration streamEnum)

Operationally, the class fulfills read requests from the first InputStream until it runs out and then switches over to the second one. In the case of an Enumeration, it will continue through all of theInputStreams until the end of the last one is reached. Here is a simple example that uses aSequenceInputStream to output the contents of two files:

// Demonstrate sequenced input. 
import java.io.*; 
import java.util.*; 
class InputStreamEnumerator implements Enumeration { 
private Enumeration files; 
public InputStreamEnumerator(Vector files) { 
this.files = files.elements(); 

public boolean hasMoreElements() { 
return files.hasMoreElements(); 

public Object nextElement() { 
try { 
return new FileInputStream(files.nextElement().toString()); 
} catch (Exception e) { 
 


return null; 



class SequenceInputStreamDemo { 
public static void main(String args[]) throws Exception { 
int c; 
Vector files = new Vector(); 
files.addElement("/autoexec.bat"); 
files.addElement("/config.sys"); 
InputStreamEnumerator e = new InputStreamEnumerator(files); 
InputStream input = new SequenceInputStream(e); 
while ((c = input.read()) != -1) { 
System.out.print((char) c); 

input.close(); 

}

This example creates a Vector and then adds two filenames to it. It passes that vector of 
names to the InputStreamEnumerator class, which is designed to provide a wrapper on 
the vector where the elements returned are not the filenames but rather open 
FileInputStream
s on those names. The SequenceInputStream opens each file in turn, 
and this example prints the contents of the two files.

'자바 > 자바팁' 카테고리의 다른 글

NIO가 무엇일까요?  (1) 2012.01.18
자바 NIO 강좌  (0) 2012.01.18
자바 압축 관련 정보  (0) 2012.01.10
JSP 및 JAVA로 오직 POST 방식으로 받을때  (0) 2011.12.13
제너릭(generic) 이해하기  (0) 2011.12.06
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.lang.StringUtils;

public class ZipUtils {

private static final int COMPRESSION_LEVEL = 8;

private static final int BUFFER_SIZE = 1024 * 2;

/**
* 지정된 폴더를 Zip 파일로 압축한다.
* @param sourcePath - 압축 대상 디렉토리
* @param output - 저장 zip 파일 이름
* @throws Exception
*/
public static void zip(String sourcePath, String output) throws Exception {

// 압축 대상(sourcePath)이 디렉토리나 파일이 아니면 리턴한다.
File sourceFile = new File(sourcePath);
if (!sourceFile.isFile() && !sourceFile.isDirectory()) {
throw new Exception("압축 대상의 파일을 찾을 수가 없습니다.");
}

// output 의 확장자가 zip이 아니면 리턴한다.
if (!(StringUtils.substringAfterLast(output, ".")).equalsIgnoreCase("zip")) {
throw new Exception("압축 후 저장 파일명의 확장자를 확인하세요");
}

FileOutputStream fos = null;
BufferedOutputStream bos = null;
ZipOutputStream zos = null;

try {
fos = new FileOutputStream(output); // FileOutputStream
bos = new BufferedOutputStream(fos); // BufferedStream
zos = new ZipOutputStream(bos); // ZipOutputStream
zos.setLevel(COMPRESSION_LEVEL); // 압축 레벨 - 최대 압축률은 9, 디폴트 8
zipEntry(sourceFile, sourcePath, zos); // Zip 파일 생성
zos.finish(); // ZipOutputStream finish
} finally {
if (zos != null) {
zos.close();
}
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
}
}
}

/**
* 압축
* @param sourceFile
* @param sourcePath
* @param zos
* @throws Exception
*/
private static void zipEntry(File sourceFile, String sourcePath, ZipOutputStream zos) throws Exception {
// sourceFile 이 디렉토리인 경우 하위 파일 리스트 가져와 재귀호출
if (sourceFile.isDirectory()) {
if (sourceFile.getName().equalsIgnoreCase(".metadata")) { // .metadata 디렉토리 return
return;
}
File[] fileArray = sourceFile.listFiles(); // sourceFile 의 하위 파일 리스트
for (int i = 0; i < fileArray.length; i++) {
zipEntry(fileArray[i], sourcePath, zos); // 재귀 호출
}
} else { // sourcehFile 이 디렉토리가 아닌 경우
BufferedInputStream bis = null;
try {
String sFilePath = sourceFile.getPath();
String zipEntryName = sFilePath.substring(sourcePath.length() + 1, sFilePath.length());

bis = new BufferedInputStream(new FileInputStream(sourceFile));
ZipEntry zentry = new ZipEntry(zipEntryName);
zentry.setTime(sourceFile.lastModified());
zos.putNextEntry(zentry);

byte[] buffer = new byte[BUFFER_SIZE];
int cnt = 0;
while ((cnt = bis.read(buffer, 0, BUFFER_SIZE)) != -1) {
zos.write(buffer, 0, cnt);
}
zos.closeEntry();
} finally {
if (bis != null) {
bis.close();
}
}
}
}

/**
* Zip 파일의 압축을 푼다.
*
* @param zipFile - 압축 풀 Zip 파일
* @param targetDir - 압축 푼 파일이 들어간 디렉토리
* @param fileNameToLowerCase - 파일명을 소문자로 바꿀지 여부
* @throws Exception
*/
public static void unzip(File zipFile, File targetDir, boolean fileNameToLowerCase) throws Exception {
FileInputStream fis = null;
ZipInputStream zis = null;
ZipEntry zentry = null;

try {
fis = new FileInputStream(zipFile); // FileInputStream
zis = new ZipInputStream(fis); // ZipInputStream

while ((zentry = zis.getNextEntry()) != null) {
String fileNameToUnzip = zentry.getName();
if (fileNameToLowerCase) { // fileName toLowerCase
fileNameToUnzip = fileNameToUnzip.toLowerCase();
}

File targetFile = new File(targetDir, fileNameToUnzip);

if (zentry.isDirectory()) {// Directory 인 경우
FileUtils.makeDir(targetFile.getAbsolutePath()); // 디렉토리 생성
} else { // File 인 경우
// parent Directory 생성
FileUtils.makeDir(targetFile.getParent());
unzipEntry(zis, targetFile);
}
}
} finally {
if (zis != null) {
zis.close();
}
if (fis != null) {
fis.close();
}
}
}

/**
* Zip 파일의 한 개 엔트리의 압축을 푼다.
*
* @param zis - Zip Input Stream
* @param filePath - 압축 풀린 파일의 경로
* @return
* @throws Exception
*/
protected static File unzipEntry(ZipInputStream zis, File targetFile) throws Exception {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(targetFile);

byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = zis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} finally {
if (fos != null) {
fos.close();
}
}
return targetFile;
}
}

위의 소스는 문제점이 있다.
사실 소스문제라기 보다는 java.util.zip 문제이다.
zip 파일안의 파일명의 인코딩을 UTF-8 로 하기 때문에 압축 대상 파일명에 한글이 있을경우 문제가 생긴다.
만약 압축 대상 파일명에 한글이 포함되어 있다면 jazzlib 를 사용하기 바란다.

jazzlib 는 java.util.zip 과 구조 및 사용법이 똑같으므로 위의 소스에서 ZipEntry, ZipOutputStream 의 import 문만 변경하여 주면 된다.

import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipInputStream;

'자바 > 자바팁' 카테고리의 다른 글

자바 NIO 강좌  (0) 2012.01.18
[자바팁]SequenceInputStream example  (1) 2012.01.11
JSP 및 JAVA로 오직 POST 방식으로 받을때  (0) 2011.12.13
제너릭(generic) 이해하기  (0) 2011.12.06
SWT Deginer 사용하기  (0) 2011.11.02
출처 : http://stackoverflow.com/questions/1197729/retrieve-post-parameters-only-java
public
boolean isInQuery(HttpServletRequest request, String key) {
 
String query = request.getQueryString();
 
String[] nameValuePairs = query.split("&");
 
for(String nameValuePair: nameValuePairs) {
   
if(nameValuePair.startsWith(key + "=")) {
     
return true;
   
}
 
}
 
return false;
}

'자바 > 자바팁' 카테고리의 다른 글

[자바팁]SequenceInputStream example  (1) 2012.01.11
자바 압축 관련 정보  (0) 2012.01.10
제너릭(generic) 이해하기  (0) 2011.12.06
SWT Deginer 사용하기  (0) 2011.11.02
AD인증 자바코드  (0) 2011.11.02
출처 : http://take0415.blog.me/60128721068
 

public class Sample2 {
public Sample2() {
}

public static void main(String[] args) {
Tmp<String> tmp1 = new Tmp<String>();
tmp1.setTmp(" s t r i n g ");
System.out.println(tmp1.getTmp());

Tmp<Integer> tmp2 = new Tmp<Integer>();
tmp2.setTmp(1);
System.out.println(tmp2.getTmp());
}
}

class Tmp<T> {
private T tmp = null;

public T getTmp() {
return tmp;
}

public void setTmp(T tmp) {
this.tmp = tmp;
}
}

이런 야리꾸리한 허접스런 티가 나는 클래스가 있다고 치자.

언듯 생각하면 제네릭의 원리는 컴파일러가 내부에서 Tmp<Integer> 와 Tmp<String> 의 각각의 클래스를 생성했을 것도 같지만
이렇게 되면 만약 여러개의 형을 사용했을 때 계속해서 코드는 증가하고 형 또한 증가할 것이다.

자바의 컴파일러는 제네릭을 만났을 때 아예 삭제 시켜 버리고 캐스팅이 필요한 곳에 캐스팅을 추가하는 방식으로 되어 있다.

예를 들자면

Tmp<String> tmp1 = new Tmp<String>();
tmp1.setTmp(" s t r i n g ");
System.out.println(tmp1.getTmp());

이 부분이

Tmp tmp1 = new Tmp();
tmp1.getTmp(" s t r i n g ");
(String) tmp1.getTmp();

[출처] 자바의 Generic의 원리|작성자 정서

'자바 > 자바팁' 카테고리의 다른 글

자바 압축 관련 정보  (0) 2012.01.10
JSP 및 JAVA로 오직 POST 방식으로 받을때  (0) 2011.12.13
SWT Deginer 사용하기  (0) 2011.11.02
AD인증 자바코드  (0) 2011.11.02
AD(ldap) 테스트용 Java 코드  (0) 2011.11.02


SWT를 본격적으로 시작하기에 앞서서~

Eclipse에서 SWT를 쉽게 사용할 수 있는게 없을까... 하고 찾아봤더니~

있더라~ ㅋㅋㅋ

게다가 아주 잘 설명해놓은 블로그 포스팅까지 발견!
블로그 쥔장님 캄사캄사해요~


- Eclipse에서 SWT Designer 사용하기 - 첫번째.
http://huikyun.tistory.com/221


- Eclipse에서 SWT Designer 사용하기 - 두번째.
http://huikyun.tistory.com/222


- Eclipse에서 SWT Designer 사용하기 - 세번째. 
http://huikyun.tistory.com/223 
.
.
.
.
.
.
.
점심 먹고와서 포스트를 따라해보려고 했는데...................... ㅡㅡ;
포스팅에서 언급한 SWT Designer제작사 망한듯...
.
.
.
.
.
.
.
알아보니, SWT Designer가 구글에 합병되었다네... 헐;
구글에서 SWT Designer, GWT Designer를 포함하여 
WindowBuilder Pro라는 이름으로 배포하고 있댄다.
그래서, 찾아가봤다.

Window Builder Pro 
- 퀵 스타트 및 가이드
http://code.google.com/intl/ko-KR/javadevtools/wbpro/quick_start.html 
http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.wb.doc.user%2Fhtml%2Findex.html

- 다운로드.
http://code.google.com/intl/ko-KR/javadevtools/download.html
http://www.eclipse.org/windowbuilder/download.php 
참고 사이트 #2 http://coozplz.blogspot.com/2011/09/java-active-directory.html

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class ADAuthenticator
{
  private String domain;
  private String ldapHost;
  private String searchBase;

  public ADAuthenticator()
  {
    this.domain = "<your domain>";
    this.ldapHost = "ldap://<your AD controller>";
    this.searchBase = "your AD root e.g. dc=abbl,dc=org";
  }

  public ADAuthenticator(String domain, String host, String dn)
  {
    this.domain = domain;
    this.ldapHost = host;
    this.searchBase = dn;
  }

  public Map authenticate(String user, String pass)
  {
    String returnedAtts[] ={ "sn", "givenName", "mail" };
    String searchFilter = "(&(objectClass=user)(sAMAccountName=" + user + "))";

    //Create the search controls
    SearchControls searchCtls = new SearchControls();
    searchCtls.setReturningAttributes(returnedAtts);

    //Specify the search scope
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapHost);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, user + "@" + domain);
    env.put(Context.SECURITY_CREDENTIALS, pass);

    LdapContext ctxGC = null;

    try
    {
      ctxGC = new InitialLdapContext(env, null);
      //Search objects in GC using filters
      NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
      while (answer.hasMoreElements())
      {
        SearchResult sr = (SearchResult) answer.next();
        Attributes attrs = sr.getAttributes();
        Map amap = null;
        if (attrs != null)
        {
          amap = new HashMap();
          NamingEnumeration ne = attrs.getAll();
          while (ne.hasMore())
          {
            Attribute attr = (Attribute) ne.next();
            amap.put(attr.getID(), attr.get());
          }
          ne.close();
        }
          return amap;
      }
    }
    catch (NamingException ex)
    {
      ex.printStackTrace();
    }

    return null;
  }
  
  public static void main(String[] args) {
  ADAuthenticator ada = new ADAuthenticator("jinsub.com", "ldap://*****", "dc=jinsub,dc=com");
  Map umap = ada.authenticate("userid", "userpassword");
  if (umap == null)
  System.out.println("login failed");
  else {
   System.out.println("login succ");
  // umap has three attributes: sn, givenName, mail
  }
 }
}

[출처] AD 인증|작성자 티거

'자바 > 자바팁' 카테고리의 다른 글

제너릭(generic) 이해하기  (0) 2011.12.06
SWT Deginer 사용하기  (0) 2011.11.02
AD(ldap) 테스트용 Java 코드  (0) 2011.11.02
java socket 프로그래밍(헤더/본문포함)  (0) 2011.10.27
[JAVA]Socket Image 전송  (6) 2011.10.26
출처 : http://evilimp.tistory.com/380

AD(ldap) 테스트용 Java 코드

어제 구글링을 하다가 SF에서 찾은 소스....

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class AdTest {

 @SuppressWarnings("unchecked")
 public static void main(String[] args) throws Exception {

  String ntUserId = "검색하고자하는사용자ID";
  String ntPasswd = "검색하고자하는사용자비밀번호";
  String url = "ldap://ldap서버명";
  String domain = "LDAP도메인(대문자)"; // 회사명이 domain.com이라면 DOMAIN
  String searchBase = "DC=domain,DC=com"; // 검색대상 tree

  Hashtable env = new Hashtable();
  env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  env.put(Context.PROVIDER_URL, url);
  env.put(Context.SECURITY_AUTHENTICATION, "simple");
  env.put(Context.SECURITY_PRINCIPAL, domain + "\\" + ntUserId);
  env.put(Context.SECURITY_CREDENTIALS, ntPasswd);

  LdapContext ctx = new InitialLdapContext(env, null);
  SearchControls sc = new SearchControls();
  sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
  sc.setReturningAttributes(new String[] { "cn", "mail" });
  NamingEnumeration results = ctx.search(searchBase, "sAMAccountName=" + ntUserId, sc);
  while (results.hasMoreElements()) {
   SearchResult sr = (SearchResult) results.next();
   Attributes attrs = sr.getAttributes();
   System.out.println("attributes: " + attrs);
  }
 }
}

이녀석을 가지고 돌려보면 해당 사용자가 존재하고 비밀번호도 맞다면 등록된 mail 주소를 반환해준다.

1.     Java Server

import! java.io.BufferedReader;

import! java.io.File;

import! java.io.FileOutputStream;

import! java.io.InputStreamReader;

import! java.net.ServerSocket;

import! java.net.Socket;

 

public class TCPServer implements Runnable{

public static final int serverPort = 10200;

@Override

public void run(){

       try{

       System.out.println("대기중..");

           ServerSocket serverSocket = new ServerSocket(serverPort);

             

           while(true)

           {

              Socket sock = serverSocket.accept();

              System.out.println("수신중....");

              try{

                  BufferedReader in = new BufferedReader(new

InputStreamReader(sock.getInputStream()));

                 String str = in.readLine();

                 System.out.println("수신중인 파일 이름 : " + str);

                 File f = new File("c:\\down\\", str+".jpg");

                 FileOutputStream output = new FileOutputStream(f);

                 byte[] buf = new byte[1024];                                       while(sock.getInputStream().read(buf)>0)

                 {

                    output.write(buf);

                    output.flush();

                 }

                 in.close();

                 output.close();

                 System.out.println(str+".jpg 수신완료");

             }

             catch(Exception e){

                 System.out.println("서버 에러!!");

                 e.printStackTrace();

             }

             finally{

                 sock.close();

             }

           }

       }

       catch(Exception e){

           e.printStackTrace();

       }

}

public static void main(String[] argv){

Thread doit = new Thread(new TCPServer());

       doit.start();

}

}

서버소켓을 생성하고 안드로이드 에뮬레이터에서 보내오는 스트림 데이터를 설정된 경로에FileOutputStream클래스를 이용하여 저장한다.

 

 

2.     Android Client

-       TCPClient.java

package sm.bit.sock;

 

import! java.io.BufferedWriter;

import! java.io.DataInputStream;

import! java.io.DataOutputStream;

import! java.io.File;

import! java.io.FileInputStream;

import! java.io.OutputStreamWriter;

import! java.io.PrintWriter;

import! java.net.InetAddress;

import! java.net.Socket;

 

public class TCPClient implements Runnable{

private static final String serverIP="192.168.34.52";

private static final int serverPort = 10200;

private String msg;

public TCPClient(String msg){

       super();

       this.msg = msg;

}

@Override

public void run(){

try{

           InetAddress serverAddr = InetAddress.getByName(serverIP);

           Socket sock = new Socket(serverAddr, serverPort);

           try{

            PrintWriter out = new PrintWriter(new BufferedWriter(new

OutputStreamWriter(sock.getOutputStream())), true);

               out.println(msg);

               out.flush();

                          

               DataInputStream dis = new DataInputStream(new

FileInputStream(new File("/mnt/sdcard/"+msg+".jpg")));

               DataOutputStream dos = new

DataOutputStream(sock.getOutputStream());

               byte[] buf = new byte[1024];

               while(dis.read(buf)>0)

               {

                  dos.write(buf);

                  dos.flush();

               }

               dos.close();

           }

           catch(Exception e){

               e.printStackTrace();

           }

           finally

           {

              sock.close();

           }

}

catch(Exception e){

             e.printStackTrace();

}

}

}

소켓을 생성하고 안드로이드 에뮬레이터의 sdcard 있는 사진 파일을 검색해서DataOutputStream 클래스로 패킷화 하여 소켓으로 전송한다.

 

-       Sock.java

package sm.bit.sock;

import! android.app.Activity;

import! android.os.Bundle;

import! android.view.View;

import! android.view.View.[안내]태그제한으로등록되지않습니다-xxOnClickListener;

import! android.widget.Button;

import! android.widget.EditText;

import! android.widget.TextView;

 

public class Sock extends Activity {

    private EditText myet;

    private TextView mytv;

    private Button mybtn;

    public String remsg;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

       

        myet = (EditText)findViewById(R.id.edit);

        mytv = (TextView)findViewById(R.id.text);

        mybtn = (Button)findViewById(R.id.sendbtn);

        mybtn.set[안내]태그제한으로등록되지않습니다-xxOnClickListener(new [안내]태그제한으로등록되지않습니다-xxOnClickListener(){

            @Override

           public void [안내]태그제한으로등록되지않습니다-xxonClick(View v){

                if((mybtn.getText().toString() != null)&&

(!mybtn.getText().toString().equals(""))){

                   TCPClient tp = new TCPClient(myet.getText().toString());

                   tp.run();

                     

                   mytv.setText(myet.getText().toString());

                   myet.setText("");

                }

            }

        });

    }

}

 


3.     실행 결과

-       Java

 

-       Android

 

 

첨부파일 [조별스터디 Android] 안드로이드 파일전송 - ja.doc


출처:http://blog.naver.com/marine694?Redirect=Log&logNo=110106773623

출처 : http://endroid.tistory.com/entry/JAVASocket-Image-%EC%A0%84%EC%86%A1
 

두 가지의 경우가 있겠죠..

 

1. 서버가 java이고 클라이언트는 다른 언어인 경우.

2. 서버와 클라이언트 모두 java로 구현하는 경우.

 

각각 다른 방식으로 프로그래밍을 할 수 있습니다.

1의 경우가 좀더 범용적이겠죠..

 

두 가지를 모두 말씀드리겠습니다.

 

- 1번의 경우...

  일반적으로 통신은 byte 단위로 이루어집니다.

  따라서 file을 읽으면 Image 클래스로 읽지 마시고, FileInputStream으로 읽으셔서

  byte 단위로 전송하는 방법입니다. 전송할 파일의 크기를 클라이언트쪽에서 알 수 없으므로,

  먼저 파일의 크기를 전송하고, 파일의 내용을 보내게 됩니다.

  클라이언트도 byte 단위로 받게 되므로 받는것을 그대로 FileOutputStream으로 쓰게 되면

  원본 이미지가 그대로 저장되게 됩니다.

 

  * sample code -- server side

  ServerSocket ssock = new ServerSocket(<server port>);

  Socket csock = NULL;

  byte buffer[] = new byte[2048];

  ...

  File imgfile = new File(<image file>);

  String flen = String.valueOf(imgfile.length());

  // change "1234" to "0000001234", to make sure 10 size.

  String header = "0000000000".substring(0, 10-flen.length()) + flen;

  while ((csock = ssock.accept()) != NULL) {

    FileInputStream fis = new FileInputStream(imgfile);

    OutputStream os = csock.getOutputStream();

    // send header

    os.write(header.getBytes());

    // send body

    while (fis.available() > 0) {

      int readsz = fis.read(buffer);

      os.write(buffer, 0, readsz);

    }

    os.close();

    fis.close();

  }

  ...

 

  * sample code -- client side

  Socket sock = new Socket(<server address>, <server port>);

  ...

  FileOutputStream fos = new FileOutputStream(<image file to be saved>);

  InputStream is = sock.getInputStream();

  byte buffer[] = new byte[2048];

  // read header(10 bytes)

  is.read(buffer, 0, 10);

  String header = new String(buffer, 0, 10);

  int bodysize = Integer.parseInt(header);

  int readsize = 0;

  // read body

  while (readsize < bodysize) {

    int rsize = is.read(buffer);

    fos.write(buffer, 0, rsize);

    readsize += rsize;

  }

  is.close();

  fos.close();

 

 

2. 서버와 클라이언트 양쪽이 모두 java인 경우

  아주 심플합니다. java 자체에서 객체전송을 허용하기 때문에

  ObjectInputStream과, ObjectOutputStream을 사용하면 됩니다.

 

  * sample code -- server side

  Image img = ImageIO.read(new File(<image file>));

  ServerSocket ssock = new ServerSocket(<server port>);

  Socket csock = NULL;

  ...

  while ((csock = ssock.accept()) != NULL) {

    ObjectOutputStream oos = new ObjectOutputStream(csock.getOutputStream());
    // send image

    oos.writeObject(img);

    oos.close();

    csock.close();

  }

  ...

 

  * sample code -- client side

  Socket sock = new Socket(<server address>, <server port>);

  ...

  ObjectInputStream ois = new ObjectInputStream(sock.getInputStream())

  Image img = (Image)ois.readObject();

  ois.close();

  sock.close();

  ...

 

이 외에도 ImageIO에서 제공하는 형태의 ImageInputStream, ImageOutputStream 등등도 있지만,

위의 두 형태가 가장 많이 사용됩니다.

 

범용적으로 쓰시려면 1번의 방법을 추천합니다.

출처 : http://cafe.naver.com/javacircle.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=36277&

Socket을 이용한 서버로 파일 송수신 예제 입니다.

 

// FileServer.java

import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

public class FileServer implements Runnable{
    private final int PORT = 25573;

    public static void main(String[] args) {
        new Thread(new FileServer() ).start();
    }

    public void run() {
        ServerSocket s = null;
        try {
            s = new ServerSocket(PORT);
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        while (s != null) {
            try {
                Socket client = s.accept();
                System.out.println("client = " + client.getInetAddress());
                new Threadnew FileServerClient(client) ).start();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static class FileServerClient implements Runnable {
        private Socket socket;

        FileServerClient( Socket s) {
            socket = s;
        }

        public void run() {
            try {
                BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
                FileInputStream fileIn = new FileInputStream"/home/warner/yoursourcefile.ext");
                byte[] buffer = new byte[8192];
                int bytesRead =0;
                while ((bytesRead = fileIn.read(buffer)) > 0) {
                    out.write(buffer, 0, bytesRead);
                }
                out.flush();
                out.close();
                fileIn.close();

            }
            catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    socket.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

 

------------------------------------------------------------------------

// FileClient.java

import java.net.Socket;
import java.net.InetSocketAddress;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;

public class FileClient {
    private String hostname;
    private int port;

    public static void main(String[] args) {
        FileClient fc = new FileClient("localhost"25573);
    }

    public FileClient(String hostname, int port) {
        this.hostname = hostname;
        this.port = port;
        connect();
    }

    private void connect() {
        Socket s = new Socket();
        try {
            s.connect( new InetSocketAddress(hostname, port) );
            InputStream in = s.getInputStream();
            FileOutputStream out = new FileOutputStream("/home/warner/mydestinationfile.ext");

            byte[] buffer = new byte[8192];
            int bytesRead=0;
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
            out.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                s.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 

 

 

 

 

 

 

 

 

 

'자바 > 자바팁' 카테고리의 다른 글

java socket 프로그래밍(헤더/본문포함)  (0) 2011.10.27
[JAVA]Socket Image 전송  (6) 2011.10.26
[펌]Transfer a file via Socket  (0) 2011.10.20
[자바]소켓(CLient측) 연결 확인  (0) 2011.10.20
properties to hashmap  (0) 2011.04.11
출처 : http://www.rgagnon.com/javadetails/java-0542.html
 

A client module connects to a server then a file is sent to the client. This exemple is very simple with no authentication and hard-coded filename!

First a server module.

import java.net.*;
import java.io.*;

public class FileServer {
  public static void main (String [] args ) throws IOException {
    // create socket
    ServerSocket servsock = new ServerSocket(13267);
    while (true) {
      System.out.println("Waiting...");

      Socket sock = servsock.accept();
      System.out.println("Accepted connection : " + sock);

      // sendfile
      File myFile = new File ("source.pdf");
      byte [] mybytearray  = new byte [(int)myFile.length()];
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(mybytearray,0,mybytearray.length);
      OutputStream os = sock.getOutputStream();
      System.out.println("Sending...");
      os.write(mybytearray,0,mybytearray.length);
      os.flush();
      sock.close();
      }
    }
}

The client module

import java.net.*;
import java.io.*;

public class FileClient{
  public static void main (String [] args ) throws IOException {
    int filesize=6022386; // filesize temporary hardcoded

    long start = System.currentTimeMillis();
    int bytesRead;
    int current = 0;
    // localhost for testing
    Socket sock = new Socket("127.0.0.1",13267);
    System.out.println("Connecting...");

    // receive file
    byte [] mybytearray  = new byte [filesize];
    InputStream is = sock.getInputStream();
    FileOutputStream fos = new FileOutputStream("source-copy.pdf");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    bytesRead = is.read(mybytearray,0,mybytearray.length);
    current = bytesRead;

    // thanks to A. Cádiz for the bug fix
    do {
       bytesRead =
          is.read(mybytearray, current, (mybytearray.length-current));
       if(bytesRead >= 0) current += bytesRead;
    } while(bytesRead > -1);

    bos.write(mybytearray, 0 , current);
    bos.flush();
    long end = System.currentTimeMillis();
    System.out.println(end-start);
    bos.close();
    sock.close();
  }
}
Thanks to s.gondi for the fix (bos.flush())!

Socket s = new Socket ("123.112.221.111", 7777);

boolean result = s.isConnected();

if(result) System.out.println("서버에 연결됨");

else System.out.println("서버에 연결실패");

package org.kodejava.example.util;

import java.util.Properties;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;

public class PropertiesToMap {
    public static void main(String[] args) {
        //
        // Create a new instance of Properties.
        //
        Properties properties = new Properties();

        //
        // Populate properties with a dummy application information
        //
        properties.setProperty("app.name", "HTML Designer");
        properties.setProperty("app.version", "1.0");
        properties.setProperty("app.vendor", "HTML Designer Inc");

        //
        // Create a new HashMap and pass an instance of Properties. Properties
        // is an implementation of a Map which keys and values stored as in a
        // string.
        //
        Map<String, String> map = new HashMap<String, String>((Map) properties);

        //
        // Get the entry set of the Map and print it out.
        //
        Set propertySet = map.entrySet();
        for (Object o : propertySet) {
            Map.Entry entry = (Map.Entry) o;
            System.out.printf("%s = %s%n", entry.getKey(), entry.getValue());
        }
    }
}

네이버에서 SVN 서버도 제공한다고 한다. 사용 방법을 정리해 보려했으나 아래에 정리가 더 잘 되있다.

참고 페이지 : http://blog.ithcity.com/55

여기에 이클립스에 svn 설치 방법이 없어서 추가한다.

1. http://subversion.tigris.org 접속

2. IDE 환경에서 eclipse 선택

3. donwlaod and install 선택

4. eclipse update site (http://subclipse.tigris.org/update_1.6.x)복사

5. eclipse를 켠 후 Help - Install New Software 추가 및 모두 추가하고 next


6. SVN repository exploring 선택

7. SVN repositories 창 생성 확인

창 우측 클릭후 new->repository location 선택

이 후 부터 위의 블로그 내용 참고

'자바 > 자바팁' 카테고리의 다른 글

[자바]소켓(CLient측) 연결 확인  (0) 2011.10.20
properties to hashmap  (0) 2011.04.11
네이버 svn 설치방법  (0) 2010.12.08
[펌]자바 IO 대충 정리..(필요할때 쓰자)  (0) 2010.12.03
색상표  (0) 2010.12.02

'자바 > 자바팁' 카테고리의 다른 글

properties to hashmap  (0) 2011.04.11
네이버 svn 설치방법 참고  (0) 2010.12.09
[펌]자바 IO 대충 정리..(필요할때 쓰자)  (0) 2010.12.03
색상표  (0) 2010.12.02
[펌]압축 관련 스트림 팁  (0) 2010.12.01

출처 : http://cafe.naver.com/ccjmaster.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=133

 

=========================================================================================

 

자바에서 처리하는 입력과 출력은 스트림(Stream)에 의존하다.

 

다시 말해 모든 형태의 입력과 출력은 1byte의 흐름으로 이루어져 있다는 이야기이다.

 

그런데 이러한 작업 처리를 텍스트 기반으로 한 형태로 바꿔 준다든지, 객체 기반으로 한 형태로 바꾸어 준다든지 하는 클래스가 있다.

 

우리는 먼저 1byte의 기본 입력과 출력 클래스 몇 가지를 공부하고 다음으로 각 형태로 변경시키는 클래스를 살펴보도록 할 것이다.

 

우선 1byte의 입력과 출력 기본 클래스는 InputStream과 OutputStream이다. 각 클래스의 상속관계는 다음과 같다.

 

  OutputStream

    ▶ FileOutputStream

    ▶ ByteArrayOutputStream

    ▶ PipedOutputStream

    ▶ ObjectOutputStream

    ▶ FilterOutputStream - BufferedOutputStream

    ▶ PaintStream

    ▶ DataOutputStream

 

  InputStream

    ▶ FileInputStream

    ▶ ByteArrayInputStream

    ▶ PipedInputStream

    ▶ ObjectInputStream

    ▶ SequenceInputStream

    ▶ AudioInputStream

    ▶ StringBufferInputStream

    ▶ FilterInputStream - BufferedInputStream

    ▶ LineNumberInputStream

         PushbackInputStream

         DataInputStream

 

여기에 표시된 많은 클래스를 다 공부한다는 것은 우리가 배우고자 하는 범위를 벗어나는 것이므로

 

실제로 파일 입·출력에서 많이 쓰는 형식을 한 가지씩만 외우도록 하자.

 

1byte 출력

 

  (1) 콘솔 출력용

    FileOutputStream fos = new FileOutputStream(FileDescriptor.out);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    DataOutputStream dos = new DataOutputStream(bos);

    dos.write
 

  (2) 파일 출력용  
    File file = new File("파일명");
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    DataOutputStream dos = new DataOutputStream(bos);

    dos.write
  

  (3) 네트워크 출력용
    Socket soc = new Socket();
    BufferedOutputStream bos = new BufferedOutputStream(soc.getOutputStream());
    DataOutputStream bos = new DataOutputStream(bos);

    dos.write

 

1byte 입력

 

  (1) 콘솔 입력용

    FileInputStream fis = new FileInputStream(FileDescriptor.in);
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream(bis);
    dis.read()…
  

  (2) 파일 입력용
    File file = new File("파일명");
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream(bis);
    dis.read()…
  

  (3) 네트워크 입력용
    Socket soc = new Socket(…);
    BufferedInputStream bis = new BufferedInputStream(soc.getInputStream());
    DataInputStream bis = new DataInputStream(bis);
    dis.read()…

 

이제 간단한 형태의 입·출력 예제를 처리해 보도록 하자.

 

EX 01

 

import java.io.*;

public class Java {
  public static void main(String[] args) {
    File file = new File("C:\\java\\work\\abc.txt"); // C:\\java\\work\\abc.txt 에 대한 객체를 생성한다.
    try {
      FileOutputStream fos = new FileOutputStream(FileDescriptor.out); // 콘솔에 대한 출력 스트림을 생성한다.
      FileOutputStream fos1 = new FileOutputStream(file); // 파일에 대한 출력 스트림을 생성한다.
      byte[] data = {66, 68, 70, 72, (byte) '!'}; // B, D, F, H, ! 에 대한 배열을 생성한다.
      fos.write(data);
      fos1.write(data);
      // fos.close();
      // fos1.close();
    }catch(FileNotFoundException fnfe){
      System.err.println("파일을 못찾겠다.");
      System.exit(1);
    }catch(IOException io){
      System.err.println("파일 입출력 에러");
      System.exit(1);
    }
    System.out.println("실행 끝");
  }
}


 

EX 02

 

import java.io.*;

public class Java {
  public static void main(String[] args) throws FileNotFoundException, IOException{
    /*
    FileInputStream fis = new FileInputStream(FileDescriptor.in); // 키보드로부터 입력 객체를 생성한다.
    System.out.print("입력 = ");
    byte by = fis.read(); 
    */ 
    File file = new File("C:\\java\\work\\abc.txt"); // 파일로부터의 입력 객체를 생성한다.

    FileInputStream fis = new FileInputStream(file);  
    byte[] by = new byte[65536];
    int count = fis.read(by);
    for(int i = 0; i < count; i++){
      System.out.println(i + " : " + (char)by[i]);
    }
  }
}

 

EX03

 

import java.io.*;

public class Java {
  public static void main(String[] args) throws FileNotFoundException, IOException{
   

   /*

    < DataOutputStream을 풀어서 썼을 때의 코딩>
       File file = new File("c:\\java\\work");
       FileOutputStream fos = new FileOutputStream(file);
       BufferedOutputStream bos = new BufferedOutputStream(fos); // 512byte
       DataOutputStream dos = new DataOutputStream(bos);
   */
  
    // 1byte 출력을 위한 객체
    DataOutputStream dos1 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream

    (new File(new File  "c:\\java\\wordk"),"HJH.txt")))); // 파일에 대한 출력 객체를 생성
    dos1.writeInt(23); // int형 숫자를 출력한다. 이것은 출력하면 파일에는 4byte의 영역을 확보하고 데이터가 표시된다.

                             // 그래서 결과가 이상하게 보인다.
    dos1.writeDouble(12.345); // double형 숫자를 출력한다. 역시 int형과 마찬가지로 8byte의 영역을 확보 후 데이터 표시

    dos1.writeBytes("ABCDEFG"); // 1byte씩 문자 형태로 출력한다. 정상적으로 보인다.

    dos1.close();
  }
}

 

EX04

 

import java.io.*;

public class Java {
  public static void main(String[] args) {
    DataInputStream dis1 = null;
    try{
      dis1 = new DataInputStream(new BufferedInputStream(new FileInputStream

      (new File(new File("c:\\java\\wordk"),"HJH.txt")))); // DataInputStream 입력 객체를 생성한다.
    } catch (FileNotFoundException fnfe){}
    int a = 0;
    double b = 0.0;
    byte[] c = null;
    try{
      a = dis1.readInt(); // int형 데이터를 입력받는다. 처음 4byte를 입력받아 저장해 둔다.
      b = dis1.readDouble(); // double형으로 데이터를 입력받는다. 다음 8byte를 입력받아 double형으로 변환한다.
      c = new byte[10]; // 문자 배열을 선언한 후 그곳에 결과를 입력받는다.
    dis1.read(c);
    dis1.close();
    }catch(IOException ie){}
   
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("c = " + new String(c));
  }
}

'자바 > 자바팁' 카테고리의 다른 글

네이버 svn 설치방법 참고  (0) 2010.12.09
네이버 svn 설치방법  (0) 2010.12.08
색상표  (0) 2010.12.02
[펌]압축 관련 스트림 팁  (0) 2010.12.01
javax.swing.event 에서의 ListDataEvent 에 관한 설명  (1) 2010.11.17

컬러 이름

16진수

 

             
 red #FF0000    
crimson #DC143C    
firebrick #B22222    
maroon #800000    
darkred #8B0000    
brown #A52A2A    
sienna #A0522D    
saddlebrown #8B4513    
indianred #CD5C5C    
rosybrown #BC8F8F    
lightcoral #F08080    
salmon #FA8072    
darksalmon #E9967A    
coral #FF7F50    
tomato #FF6347    
sandybrown #F4A460    
lightsalmon #FFA07A    
peru #CD853F    
chocolate #D2691E    
orangered #FF4500    
orange #FFA500    
darkorange #FF8C00    
tan #D2B48C    
peachpuff #FFDAB9    
bisque #FFE4C4    
moccasin #FFE4B5    
navajowhite #FFDEAD    
wheat #F5DEB3    
burlywood #DEB887    
darkgoldenrod #B8860B    
goldenrod #DAA520    
gold #FFD700    
yellow #FFFF00    
lightgoldenrodyellow #FAFAD2    
palegoldenrod #EEE8AA    
khaki #F0E68C    
darkkhaki #BDB76B    
lawngreen #7CFC00    
greenyellow #ADFF2F    
chartreuse #7FFF00    
lime #00FF00    
limegreen #32CD32    
yellowgreen #9ACD32    
olive #808000    
olivedrab #6B8E23    
darkolivegreen #556B2F    
forestgreen #228B22    
darkgreen #006400    
green #008000    
seagreen #2E8B57    
mediumseagreen #3CB371    
darkseagreen #8FBC8F    
lightgreen #90EE90    
palegreen #98FB98    
springgreen #00FF7F    
mediumspringgreen #00FA9A    
teal #008080    
darkcyan #008B8B    
lightseagreen #20B2AA    
mediumaquamarine #66CDAA    
cadetblue #5F9EA0    
steelblue #4682B4    
aquamarine #7FFFD4    
powderblue #B0E0E6    
paleturquoise #AFEEEE    
lightblue #ADD8E6    
lightsteelblue #B0C4DE    
skyblue #87CEEB    
lightskyblue #87CEFA    
mediumturquoise #48D1CC    
turquoise #40E0D0    
darkturquoise #00CED1    
aqua #00FFFF    
cyan #00FFFF    
deepskyblue #00BFFF    
dodgerblue #1E90FF    
cornflowerblue #6495ED    
royalblue #4169E1    
blue #0000FF    
mediumblue #0000CD    
navy #000080    
darkblue #00008B    
midnightblue #191970    
darkslateblue #483D8B    
slateblue #6A5ACD    
mediumslateblue #7B68EE    
mediumpurple #9370DB    
darkorchid #9932CC    
darkviolet #9400D3    
blueviolet #8A2BE2    
mediumorchid #BA55D3    
plum #DDA0DD    
lavender #E6E6FA    
thistle #D8BFD8    
orchid #DA70D6    
violet #EE82EE    
indigo #4B0082    
darkmagenta #8B008B    
purple #800080    
mediumvioletred #C71585    
deeppink #FF1493    
fuchsia #FF00FF    
magenta #FF00FF    
hotpink #FF69B4    
palevioletred #DB7093    
lightpink #FFB6C1    
pink #FFC0CB    
mistyrose #FFE4E1    
blanchedalmond #FFEBCD    
lightyellow #FFFFE0    
cornsilk #FFF8DC    
antiquewhite #FAEBD7    
papayawhip #FFEFD5    
lemonchiffon #FFFACD    
beige #F5F5DC    
linen #FAF0E6    
oldlace #FDF5E6    
lightcyan #E0FFFF    
aliceblue #F0F8FF    
whitesmoke #F5F5F5    
lavenderblush #FFF0F5    
floralwhite #FFFAF0    
mintcream #F5FFFA    
ghostwhite #F8F8FF    
honeydew #F0FFF0    
seashell #FFF5EE    
ivory #FFFFF0    
azure #F0FFFF    
snow #FFFAFA    
white #FFFFFF    
gainsboro #DCDCDC    
lightgrey #D3D3D3    
silver #C0C0C0    
darkgray #A9A9A9    
lightslategray #778899    
slategray #708090    
gray #808080    
dimgray #696969    
darkslategray #2F4F4F    
black #000000    


[출처] : http://bluejames77.blog.me/80015770905

자바에서 압축을 할려면 ZipInputStream과 GZIPInputStream을 써야 합니다.

 

이것을 이용해서 압축하는 예제를 JUNIT으로 만들어 보았습니다.

 

일단 예제를 보여드리기에 설명을 드리겠습니다.

 

1. ZipInputStream과 GZIPInputStream과의 차이점은 무엇인가요?

=> 쉽게 zip은 원도우에서 gzip은 유닉스나 리눅스에서 쓴다고 보시면 됩니다.

그러나 원도우에서도 gzip으로 압축해도 됩니다. gzip으로 하면 한글도 잘 압축됩니다.

zip은 한글 압축이 안되는데 이것은 따로 말씀드리도록 하겠습니다.

그리고 zip은 여러개를 한꺼번에 압축이 가능합니다. gzip은 지원이 안됩니다.

 

2. java.util.zip.ZipInputStream은 왜 한글 문서는 압축할 수가 없나요?

=> 이것은 썬의 버그라고 합니다. 썬것으로는 영문파일밖에는 안됩니다 -0-;

그래서 만약 한글 문서도 압축할려고 할려면 외국 개발자가 픽스해 놓은 클래스를 써야 합니다.

이것은 제가 첨부파일로 올려 놓겠습니다.

자세한 것은 이 URL을 참조하세요 마지막 덧글에 제 아이디도 보입니다 -_-a

http://www.javaservice.net/~java/bbs/read.cgi?m=resource&b=jdk&c=r_p&n=1100737475&k=압축&d=tb#1100737475

아래는 okjsp에서 pistos님이 답변해준 내용입니다.

java.util.zip은 압축파일내의 파일명 인코딩을 UTF-8로 처리해서 그래요.. 
zip 포맷이라는게 압축파일내의 파일명에 사용하는 인코딩을 지정하지 않았고, OS마다 encoding이 달라서 썬에서는 요걸 UTF-8로 정해놓고 쓰기로 한거라네요.. 
다음 버그리포트를 참고하시면 될거구요.. 

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499

 

3. flush()와 close()의 차이점과 쓰는 용도를 알고 싶습니다.

=> 스트림은 하나의 관이라고 보시면 됩니다 예를 들어 하수관 -_-;

즉 바이트의 흐름입니다. 중요한게 입력스트림은 입력만 가능하고 출력 스트림은 출력만 가능합니다.

생각해보세요 물을 받는 호스에서 갑자기 물이 역류한다면? 이 무슨 황당한 시츄에이션? 말이 안되죠? ^^;

flush()는 있는 물을 쏟아 버린다고 생각하시면 됩니다.

그래서 출력스트림에서 flush()를 해버리면.. 있는것을 다 털어 버리는거죠 예를 들면 호수를 탈탈 터는것!

그리고 close()는 수도 꼭지를 잠그는 것이라고 생각하면 됩니다. 우리가 보통 수도꼭지 잠글때 호스도 털죠?

호스 다 썼으니깐 털어야 하잖아요. ^^;

그래서 close()를 하면 호스를 털고[flush()] 수도꼭지를 잠근것[close()]한 것과 같은 의미입니다. 

close()하고 다시 쓸려면? open은 따로 없습니다. ^^; 다시 생성하셔야 합니다. 

 

4. ZipInputStream에만 있는 ZipEntry가 무슨 역할을 하는 것인가요?

=> ZipInputStream은 1번에서 말씀드렸다시피 여러개의 파일을 한꺼번에 압축할 수 있습니다.

원래 ZIP 파일이란 것이 하나 이상의 압축 파일을 포함하는데, 이때 각각의 파일은 ZIP 엔트리(Zip Entry)라고 합니다
Zip 엔트리는 ZipEntry 클래스의 객체로 표현되며, ZipEntry는 엔트리의 이름인 String 객체를 취하는 생성자를 가집니다.

이것도 예제(testFileZipComplex)를 보시면 금방 이해가 가실것입니다.

 

5. 이것도 디비처럼 꼭 close() 해줘야 하나요?

=> 넵 말이 필요없습니다!. 철저한 자원관리! ^-^;

예제를 보시면 제가 앞의 메소드들은 안하다가 뒤로 갈수록 했는데요.. 사실 이러시면 안됩니다!!

실전에서는 꼭 finally에서 닫아주는 센스!! 잊지마세요.

 

예제는 총 7개가 있습니다.
1. atestFileCopy 
 -> 파일카피 (스트림의 기본이라서 넣어 봤습니다 ^^;)
2. atestFileZipSimple
 -> 단순한 파일 압축. 한글깨지는 문제가 있음. 썬의 버그임 외국개발자가 버그 픽스한 라이브러리로 처리.
3. btestFileZipSimple2
 -> // 간단 압축된 파일 풀깅~ 
4. atestFileZipInOut2()
 -> ZipOutputStream을 이용한 압축 및 해제. 순서 1. 원본파일 -> 압축 -> 압축해제 후 원본파일 복귀
5. atestArrayFileZip()
 -> ZipOutputStream의 setLevel을 1-9까지 돌려보며 속도와 압축률 비교.
6. atestFileGZipInOut()
 -> GZIPOutputStream을 이용한 압축 및 해제. 순서 1.원본파일->압축->압축해제 후 원본파일복귀
7. testFileZipComplex
 -> 여러개의  파일을 하나의 zip파일로 압축.

 

소스 보시면 다 이해가 갈것입니다. 맛배기로 5번의 결과값을 보여드립니다. ^-^;

 

자바 디폴트 압축레벨8

Catalysis소개0.zip make Sucessed
Catalysis소개0.zip Size = 2086874 byte
 압축에 걸린 시간 측정 220 millisecond

Catalysis소개1.zip make Sucessed
Catalysis소개1.zip Size = 1548156 byte
 압축에 걸린 시간 측정 421 millisecond

Catalysis소개2.zip make Sucessed
Catalysis소개2.zip Size = 1541146 byte
 압축에 걸린 시간 측정 411 millisecond

Catalysis소개3.zip make Sucessed
Catalysis소개3.zip Size = 1534771 byte
 압축에 걸린 시간 측정 440 millisecond

Catalysis소개4.zip make Sucessed
Catalysis소개4.zip Size = 1526945 byte
 압축에 걸린 시간 측정 481 millisecond

Catalysis소개5.zip make Sucessed
Catalysis소개5.zip Size = 1520943 byte
 압축에 걸린 시간 측정 541 millisecond

Catalysis소개6.zip make Sucessed
Catalysis소개6.zip Size = 1516023 byte
 압축에 걸린 시간 측정 510 millisecond

Catalysis소개7.zip make Sucessed
Catalysis소개7.zip Size = 1515002 byte
 압축에 걸린 시간 측정 561 millisecond

Catalysis소개8.zip make Sucessed
Catalysis소개8.zip Size = 1513484 byte
 압축에 걸린 시간 측정 922 millisecond

Catalysis소개9.zip make Sucessed
Catalysis소개9.zip Size = 1512840 byte
 압축에 걸린 시간 측정 1081 millisecond

 

보시면 알겠지만 setLevel이 높을수록 압축률이 높고 속도가 떨어집니다. ^^;

디폴트는 8입니다.

 

ZipInputStream을 이해하는데 많은 도움이 되었으면 합니다. ^-^;

 

ps1 jazzlib_0.07은 외국개발자가 픽스해 놓은 소스.

      jazzlib.zip은 제가 위의 소스를 jar로 묶은것.

 

ps2 틀린점이나 추가할 사항이 있으시면 지적해 주는 센스!! 아시죠? ^^


ListDataEvent.CONTENTS_CHANGED

/*Type: Interval Added
, Index0: 0
, Index1: 0
[First, a, b, c, d]
Type: Interval Added
, Index0: 5
, Index1: 5
[First, a, b, c, d, Last]
Type: Interval Added
, Index0: 3
, Index1: 3
[First, a, b, Middle, c, d, Last]
Type: Contents Changed
, Index0: 0
, Index1: 0
[New First, a, b, Middle, c, d, Last]
Type: Contents Changed
, Index0: 6
, Index1: 6
[New First, a, b, Middle, c, d, New Last]
Type: Interval Added
, Index0: 7
, Index1: 7
[New First, a, b, Middle, c, d, New Last, a]
Type: Interval Added
, Index0: 8
, Index1: 8
[New First, a, b, Middle, c, d, New Last, a, b]
Type: Interval Added
, Index0: 9
, Index1: 9
[New First, a, b, Middle, c, d, New Last, a, b, c]
Type: Interval Added
, Index0: 10
, Index1: 10
[New First, a, b, Middle, c, d, New Last, a, b, c, d]
Type: Interval Removed
, Index0: 0
, Index1: 10
[]

 * */
import java.awt.BorderLayout;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class MainClass {
  static String labels[] "a""b""c""d" };

  public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
      model.addElement(labels[i]);
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.WEST);

    ListDataListener listDataListener = new ListDataListener() {
      public void contentsChanged(ListDataEvent listDataEvent) {
        appendEvent(listDataEvent);
      }
      public void intervalAdded(ListDataEvent listDataEvent) {
        appendEvent(listDataEvent);
      }
      public void intervalRemoved(ListDataEvent listDataEvent) {
        appendEvent(listDataEvent);
      }
      private void appendEvent(ListDataEvent listDataEvent) {
        switch (listDataEvent.getType()) {
        case ListDataEvent.CONTENTS_CHANGED:
          System.out.println("Type: Contents Changed");
          break;
        case ListDataEvent.INTERVAL_ADDED:
          System.out.println("Type: Interval Added");
          break;
        case ListDataEvent.INTERVAL_REMOVED:
          System.out.println("Type: Interval Removed");
          break;
        }
        System.out.println(", Index0: " + listDataEvent.getIndex0());
        System.out.println(", Index1: " + listDataEvent.getIndex1());
        DefaultListModel theModel = (DefaultListModellistDataEvent.getSource();
        System.out.println(theModel);
      }
    };

    model.addListDataListener(listDataListener);

    model.add(0"First");
    model.addElement("Last");
    int size = model.getSize();
    model.insertElementAt("Middle", size / 2);
    size = model.getSize();
    if (size != 0)
      model.set(0"New First");
    size = model.getSize();
    if (size != 0)
      model.setElementAt("New Last", size - 1);
    for (int i = 0, n = labels.length; i < n; i++) {
      model.addElement(labels[i]);
    }
    model.clear();
    size = model.getSize();
    if (size != 0)
      model.remove(0);

    model.removeAllElements();
    model.removeElement("Last");
    size = model.getSize();
    if (size != 0)
      model.removeElementAt(size / 2);
    size = model.getSize();
    if (size != 0)
      model.removeRange(0, size / 2);
    frame.setSize(640300);
    frame.setVisible(true);
  }
}


사용법 : File file = new FileRenamePolicy().rename(new File(원하는 파일명));

==============================================================================
import java.io.File;
import java.io.IOException;

public class FileRenamePolicy {
 
  public File rename(File f) {  //File f는 원본 파일
    if (createNewFile(f)) return f; //생성된 f가
   
    //확장자가 없는 파일 일때 처리
    String name = f.getName();
    String body = null;
    String ext = null;

    int dot = name.lastIndexOf(".");
    if (dot != -1) { //확장자가 없을때
      body = name.substring(0, dot);
      ext = name.substring(dot);
    } else {   //확장자가 있을때
      body = name;
      ext = "";
    }

    int count = 0;
    //중복된 파일이 있을때
    while (!createNewFile(f) && count < 9999) {  
      count++;
      String newName = body + count + ext;
      f = new File(f.getParent(), newName);
    }
    return f;
  }

  private boolean createNewFile(File f) { 
    try {
      return f.createNewFile();  //존재하는 파일이 아니면
    }catch (IOException ignored) {
      return false;
    }
  }
}

Introduction to Object Serialization

Java object serialization is used to persist Java objects to a file, database, network, process or any other system. Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered stream of bytes can then be read at a later time, or in another environment, to recreate the original objects.

Java serialization does not cannot occur for transient or static fields. Marking the field transient prevents the state from being written to the stream and from being restored during deserialization. Java provides classes to support writing objects to streams and restoring objects from streams. Only objects that support the java.io.Serializable interface or the java.io.Externalizable interface can be written to streams.
public interface Serializable

  • The Serializable interface has no methods or fields. (Marker Interface)
  • Only objects of classes that implement java.io.Serializable interface can be serialized or deserialized

Transient Fields and Java Serialization

The transient keyword is a modifier applied to instance variables in a class. It specifies that the variable is not part of the persistent state of the object and thus never saved during serialization.

You can use the transient keyword to describe temporary variables, or variables that contain local information,


such as a process ID or a time lapse.

Input and Output Object Streams

ObjectOutputStream is the primary output stream class that implements the ObjectOutput interface for serializing objects. ObjectInputStream is the primary input stream class that implements the ObjectInput interface for deserializing objects.

These high-level streams are each chained to a low-level stream, such as FileInputStream or FileOutputStream.
The low-level streams handle the bytes of data. The writeObject method saves the state of the class by writingthe individual fields to the ObjectOutputStream. The readObject method is used to deserialize the object from
the object input stream.

Case 1: Below is an example that demonstrates object Serialization into a File

PersonDetails is the bean class that implements the Serializable interface

import java.io.Serializable;
public class PersonDetails implements Serializable {

	private String name;
	private int age;
	private String sex;
	public PersonDetails(String name, int age, String sex) {
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
}

GetPersonDetails is the class that is used to Deserialize object from the File (person.txt).

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
public class GetPersonDetails {

	public static void main(String[] args) {
		String filename = "person.txt";
		List pDetails = null;
		FileInputStream fis = null;
		ObjectInputStream in = null;
		try {
			fis = new FileInputStream(filename);
			in = new ObjectInputStream(fis);
			pDetails = (ArrayList) in.readObject();
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}
		// print out the size
		System.out.println("Person Details Size: " + pDetails.size());
		System.out.println();
	}
}

PersonPersist is the class that is used to serialize object into the File (person.txt).

public class PersonPersist {

	public static void main(String[] args) {
		String filename = "person.txt";
		PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
		PersonDetails person2 = new PersonDetails("bob", 12, "Male");
		PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
		List list = new ArrayList();
		list.add(person1);
		list.add(person2);
		list.add(person3);
		FileOutputStream fos = null;
		ObjectOutputStream out = null;
		try {
			fos = new FileOutputStream(filename);
			out = new ObjectOutputStream(fos);
			out.writeObject(list);
			out.close();
			System.out.println("Object Persisted");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

——————————————————————————–

Case 2: Below is an example that demonstrates object Serialization into the database

PersonDetails remains the same as shown above

GetPersonDetails remains the same as shown above

Create SerialTest Table

create table SerialTest(
name BLOB,
viewname VARCHAR2(30)
);

PersonPersist is the class that is used to serialize object into the into the Database Table SerialTest.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {

	static String userid = "scott", password = "tiger";
	static String url = "jdbc:odbc:bob";
	static int count = 0;
	static Connection con = null;
	public static void main(String[] args) {
		Connection con = getOracleJDBCConnection();
		PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
		PersonDetails person2 = new PersonDetails("bob", 12, "Male");
		PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
		PreparedStatement ps;
		try {
			ps = con
					.prepareStatement("INSERT INTO SerialTest VALUES (?, ?)");
			write(person1, ps);
			ps.execute();
			write(person2, ps);
			ps.execute();
			write(person3, ps);
			ps.execute();
			ps.close();
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery("SELECT * FROM SerialTest");
			while (rs.next()) {
				Object obj = read(rs, "Name");
				PersonDetails p = (PersonDetails) obj;
				System.out.println(p.getName() + "\t" + p.getAge() + "\t"
						+ p.getSex());
			}
			rs.close();
			st.close();
		} catch (Exception e) {
		}
	}
	public static void write(Object obj, PreparedStatement ps)
			throws SQLException, IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oout = new ObjectOutputStream(baos);
		oout.writeObject(obj);
		oout.close();
		ps.setBytes(1, baos.toByteArray());
		ps.setInt(2, ++count);
	}
	public static Object read(ResultSet rs, String column)
			throws SQLException, IOException, ClassNotFoundException {
		byte[] buf = rs.getBytes(column);
		if (buf != null) {
			ObjectInputStream objectIn = new ObjectInputStream(
					new ByteArrayInputStream(buf));
			return objectIn.readObject();
		}
		return null;
	}
	public static Connection getOracleJDBCConnection() {
		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		} catch (java.lang.ClassNotFoundException e) {
			System.err.print("ClassNotFoundException: ");
			System.err.println(e.getMessage());
		}
		try {
			con = DriverManager.getConnection(url, userid, password);
		} catch (SQLException ex) {
			System.err.println("SQLException: " + ex.getMessage());
		}
		return con;
	}
}

——————————————————————————–

Case 3: Below is an example that demonstrates object Serialization into the database using Base 64 Encoder

PersonDetails remains the same as shown above

GetPersonDetails remains the same as shown above

Create SerialTest Table

create table SerialTest(
name BLOB,
viewname VARCHAR2(30)
);

PersonPersist is the class that is used to serialize object into the Database Table SerialTest

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {

	static String userid = "scott", password = "tiger";
	static String url = "jdbc:odbc:bob";
	static int count = 0;
	static Connection con = null;
	static String s;
	public static void main(String[] args) {
		Connection con = getOracleJDBCConnection();
		PersonDetails person1 = new PersonDetails("hemanth", 10, "Male");
		PersonDetails person2 = new PersonDetails("bob", 12, "Male");
		PersonDetails person3 = new PersonDetails("Richa", 10, "Female");
		PreparedStatement ps;
		try {
			ps = con
					.prepareStatement("INSERT INTO SerialTest VALUES (?, ?)");
			write(person1, ps);
			ps.execute();
			write(person2, ps);
			ps.execute();
			write(person3, ps);
			ps.execute();
			ps.close();
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery("SELECT * FROM SerialTest");
			while (rs.next()) {
				Object obj = read(rs, "Name");
				PersonDetails p = (PersonDetails) obj;
				System.out.println(p.getName() + "\t" + p.getAge() + "\t"
						+ p.getSex());
			}
			rs.close();
			st.close();
		} catch (Exception e) {
		}
	}
	public static void write(Object obj, PreparedStatement ps)
			throws SQLException, IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oout = new ObjectOutputStream(baos);
		oout.writeObject(obj);
		oout.close();
		byte[] buf = baos.toByteArray();
		s = new sun.misc.BASE64Encoder().encode(buf);
		ps.setString(1, s);
		// ps.setBytes(1, Base64.byteArrayToBase64(baos.toByteArray()));
		ps.setBytes(1, baos.toByteArray());
		ps.setInt(2, ++count);
	}
	public static Object read(ResultSet rs, String column)
			throws SQLException, IOException, ClassNotFoundException {
		byte[] buf = new sun.misc.BASE64Decoder().decodeBuffer(s);
		// byte[] buf = Base64.base64ToByteArray(new
		// String(rs.getBytes(column)));
		if (buf != null) {
			ObjectInputStream objectIn = new ObjectInputStream(
					new ByteArrayInputStream(buf));
			Object obj = objectIn.readObject(); // Contains the object
			PersonDetails p = (PersonDetails) obj;
			System.out.println(p.getName() + "\t" + p.getAge() + "\t"
					+ p.getSex());
		}
		return null;
	}
	public static Connection getOracleJDBCConnection() {
		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		} catch (java.lang.ClassNotFoundException e) {
			System.err.print("ClassNotFoundException: ");
			System.err.println(e.getMessage());
		}
		try {
			con = DriverManager.getConnection(url, userid, password);
		} catch (SQLException ex) {
			System.err.println("SQLException: " + ex.getMessage());
		}
		return con;
	}
}
Below is a program that shows the serialization of a JButton object to a file and a Byte Array Stream. As before theobject to be serialized must implement the Serializable interface.

PersonDetails is the bean class that implements the Serializable interface

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class ObjectSerializationExample {

	public static void main(String args[]) {
		try {
			Object object = new javax.swing.JButton("Submit");
			// Serialize to a file namely "filename.dat"
			ObjectOutput out = new ObjectOutputStream(
					new FileOutputStream("filename.dat"));
			out.writeObject(object);
			out.close();
			// Serialize to a byte array
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			out = new ObjectOutputStream(bos);
			out.writeObject(object);
			out.close();
			// Get the bytes of the serialized object
			byte[] buf = bos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

+ Recent posts