1.자바

인터넷 url 이미지를 불러와서 로컬 서버에 쓰기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
String url = (String) mmsForm.get("imgUrlOne");
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );
 
//url = https://www.test.co.kr/image01.jpg
//fileName = image01.jpg
 
//Read Image from URL
//url 이미지를 불러온다
BufferedImage img = ImageIO.read(new URL(url));
 
//Image Write
//로딩한 이미지를 서버에 
//File file = new File("/home/dev/imageRoot/"+fileName);
File file = new File("D:\\DEV\\ImageRoot\\"+fileName);
ImageIO.write(img, "jpg", file);
cs


transferTo()

1
2
File f = new File("D:\\21.jpg");
mmsForm.getFile1().transferTo(f);
cs


multipartfile.transferTo()

이미지 URL 바이트 쓰기

1
2
3
URL url = new URL("https://test.co.kr/75.jpg");
BufferedImage f = ImageIO.read(url);                    
logger.debug("### test="+((DataBufferByte) f.getRaster().getDataBuffer()).getData());
cs


Java 콤마를 구분하여 배열에 담기


문자열 변수를 콤마 기준으로 잘라야 할 때는 split()을 사용하여

String[] 문자열 배열에 담도록 한다.



1
2
String salesTeam = "홍길동,유관순,강감찬";
String[] salesTeamArray = salesTeam.split(",");
cs




문자열 배열을 문자열 리스트에 담을 때는?


1
2
3
4
5
6
7
String salesTeam = "홍길동,유관순,강감찬";
String[] salesTeamArray = salesTeam.split(",");
 
List<String> salesTeamList = new ArrayList<>();
for (int i = 0; i < salesTeamArray.length; i++) {
    salesTeamList.add(salesTeamArray[i]);
}
cs


HttpClient, HttpPost, HttpResponse, HttpEntity 사용하기


HttpCliend

HttpPost

HttpResponse

HttpEntity


NameValuePair


공부해야게따ㅠㅠ



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:8080/testLatLngData");
httpPost.addHeader("Content-Type""application/x-www-form-urlencoded");
 
List<NameValuePair> testParam = new ArrayList<>();
testParam.add(new BasicNameValuePair("lat", ( "37.469997210138416" )));
testParam.add(new BasicNameValuePair("lng", ( "126.9273415126953" )));
 
httpPost.setEntity(new UrlEncodedFormEntity(testParam, "UTF-8"));
 
HttpResponse resp = httpClient.execute(httpPost);
 
HttpEntity respEntity = resp.getEntity();
 
Object obj = JSONValue.parse(new InputStreamReader(respEntity.getContent()));
 
//결과처리
//JSONObject jsonObject = (JSONObject) obj;
cs


MultiValueMap, RestTemplate, HttpEntity 이용하기

문자발송 코드 짜다가.. 까먹을까봐 정리해둠.


MultiValueMap parameters 에 파라미터 값들을 담고

(multipart/form-data 가 있는 경우는 MultiValueMap<String, Object> 로 하면 되는지는 테스트해봐야함)


HttpHeaders headers 에 Content-Type 정보와 클라이언트키값(api key)값을 담는다.

Content-Type 은 두 가지로 나뉘는데 RestTemplate을 사용하면 알아서 정해진다고 한다.

1
2
headers.add("Content-Type""application/x-www-form-urlencoded; charset=UTF-8"); //전부다 String형일 때. RestTemplate 쓰면 생략가능
headers.add("Content-Type""multipart/form-data; boundary=----WebKitFormBoundary8UhbmC4vAvBxT6z3"); //multipart/form-data 있는 경우 사용. RestTemplate 쓰면 생략 가능
cs



위 parameters 와 headers 를 HttpEntity<> request 에 담는다.

위에서 MultiValueMap을 <String, String>으로 선언했기 때문에 HttpEntity<MultiValueMap<String, String>> 이다.


RestTemplate.postForObject() 을 실행할 때 URI, request, String.class 변수로 넘긴다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
MultiValueMap<StringString> parameters = new LinkedMultiValueMap<>();
 
parameters.add("send_phone""12341234");
parameters.add("dest_phone""01012345678");
parameters.add("msg_body""단문 문자 테스트");
parameters.add("subject""문자 제목");
 
HttpHeaders headers = new HttpHeaders();
//headers.add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); //전부다 String형일 때. RestTemplate 때문에 생략가능
//headers.add("Content-Type", "multipart/form-data; boundary=----WebKitFormB~~3"); //multipart/form-data 있는 경우 사용. RestTemplate 때문에 생략 가능
headers.add("x-waple-authorization""API키값");
 
HttpEntity<MultiValueMap<StringString>> request = new HttpEntity<>(parameters, headers);
 
RestTemplate rest = new RestTemplate();
String result = rest.postForObject(new URI("http://api.openapi.io/ppurio/1/message/mms/API스토어ID"), request, String.class);
//결과 {“result_code”:”200”,”cmid”:”20130314163439459”}
 
// 결과값에 따른 처리
JSONObject feedback = (JSONObject) new JSONParser().parse(result);
String resultCode = (String) feedback.get("result_code");
 
cs




참고 : 

http://www.apistore.co.kr/api/apiView.do?service_seq=151

http://blog.saltfactory.net/java/post-multipart-form-data-using-resttemplate-in-spring.html

자바 AES 256 암호화 복호화

아파치에서 제공하는 패키지를 통해 자바 AES 256 암호화, 복호화를 해보기로 한다.



1.


먼저 Apache Commons Codec 패키지를 이용하기 위해서는 

Apache Commons Codec 패키지를 직접 jar 파일을 라이브러리에 수동으로 추가하거나,

Maven 의 경우 pom.xml 에 dependency 를 추가해줘야 한다.


수동으로 라이브러리를 추가하려면

http://blog.naver.com/slimcdp/220495115002

어떤 분이 잘 설명해놓으신 위 블로그 포스트를 참고하면 되고, (아래 AES256Util.java 소스나 테스트 소스도 이 포스트를 참고하였다 )


메이븐의 경우 아래 내용을 참고하면 된다.


https://mvnrepository.com/artifact/commons-codec/commons-codec

MVN Repository 사이트에서 검색하면 여러가지 버전이 있는데


1.10으로 해보기로.




위 소스코드를 그대로 복사해서 pom.xml 에 붙여넣기 하면 된다.





2. AES256Util.java 파일을 작성한다

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.test.api.utils;
 
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
 
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
import org.apache.commons.codec.binary.Base64;
 
/*
Copyright 회사명 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 
public class AES256Util {
    private String iv;
    private Key keySpec;
    
    public AES256Util(String key) throws UnsupportedEncodingException {
        this.iv = key.substring(016);
        
        byte[] keyBytes = new byte[16];
        byte[] b = key.getBytes("UTF-8");
        int len = b.length;
        if (len > keyBytes.length) {
            len = keyBytes.length;
        }
        System.arraycopy(b, 0, keyBytes, 0, len);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        
        this.keySpec = keySpec;
    }
    
 
    // 암호화
    public String aesEncode(String str) throws java.io.UnsupportedEncodingException, 
                                                    NoSuchAlgorithmException, 
                                                    NoSuchPaddingException, 
                                                    InvalidKeyException, 
                                                    InvalidAlgorithmParameterException, 
                                                    IllegalBlockSizeException, 
                                                    BadPaddingException {
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));
 
        byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
        String enStr = new String(Base64.encodeBase64(encrypted));
 
        return enStr;
    }
 
    //복호화
    public String aesDecode(String str) throws java.io.UnsupportedEncodingException,
                                                        NoSuchAlgorithmException,
                                                        NoSuchPaddingException, 
                                                        InvalidKeyException, 
                                                        InvalidAlgorithmParameterException,
                                                        IllegalBlockSizeException, 
                                                        BadPaddingException {
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes("UTF-8")));
 
        byte[] byteStr = Base64.decodeBase64(str.getBytes());
 
        return new String(c.doFinal(byteStr),"UTF-8");
    }
 
}
 
cs


3. 암호화, 복호화, URL Encoding, Decoding 테스트

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
String key = "aes256-test-key!!";    //key는 16자 이상
AES256Util aes256 = new AES256Util(key);
URLCodec codec = new URLCodec();
 
String encLoginidx = codec.encode(aes256.aesEncode(loginidx)); 
String decLoginidx = aes256.aesDecode(codec.decode(encLoginidx));
 
logger.debug("### loginidx:"+loginidx); //MEM201605090243
logger.debug("### encLoginidx:"+encLoginidx); //encoding 전 K8OcI65S+lX9MjEKN5EMdQ== / 후 K8OcI65S%2BlX9MjEKN5EMdQ%3D%3D
logger.debug("### decLoginidx:"+decLoginidx); //MEM201605090243
 
String encLat = codec.encode(aes256.aesEncode(""+Lat)); 
String decLat = aes256.aesDecode(codec.decode(encLat));
 
logger.debug("### Lat:"+Lat);    //37.71248872643193
logger.debug("### encLat:"+encLat);    //encoding 전 0FTRN5NS7FrhNsJ4GEI4Hc62CLzuTx89JUX+2Z4PvqE= / 후 0FTRN5NS7FrhNsJ4GEI4Hc62CLzuTx89JUX%2B2Z4PvqE%3D
logger.debug("### decLat:"+decLat);    //37.71248872643193
 
String encLng = codec.encode(aes256.aesEncode(""+Lng)); 
String decLng = aes256.aesDecode(codec.decode(encLng));
 
logger.debug("### Lng:"+Lng);    //127.26688771630859
logger.debug("### encLng:"+encLng);    //encoding 전 OVDlF0whDEW7MxGbJvk84Jajx4ve0tikK4YXj+Z8y6Q= / 후 OVDlF0whDEW7MxGbJvk84Jajx4ve0tikK4YXj%2BZ8y6Q%3D
logger.debug("### decLng:"+decLng);    //127.26688771630859
 
cs




그 외에, 암호화된 데이터로 넘겨받았는지 아닌지 체크하기 (암호화 된 값이라면 String형이므로 Double 로 형변환 실패할 것)

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * 암호화 된 좌표인지 확인하기 위한 임시 변수
 * 실제 복호화 할 필요가 있는지
 * 복호화 할 필요가 있으면 true 
 */
boolean aesAvail = false;
String aesLat = (String)param.get("neLat");
try{
    Double.parseDouble(aesLat);
    aesAvail = false;
catch(Exception e){
    aesAvail = true;
}

cs


API 작성을 도와주는 Javadoc

Javadoc은 API 문서에 대한 코멘트의 효율성을 높여주는 툴이다.

(DTD만 생각나고 Javadoc은 생각이 안 나서 한참을 검색함... '자바 주석 표준', '문서화 주석'이라고도 하는가보다.)

 

예를들면 클래스나 메소드에 마우스 포인트 갖다대면 뜨는 이런거..

 

 

Javadoc을 쓰려면 몇 가지 작성규칙을 따라야 한다.

예를 들면 첫번째 줄은 /** 로 시작해야 한다든지.

 

주석처리 입력하듯이 /** 엔터만 쳐도 템플릿이 자동완성 되긴 하지만,

이클립스 단축키 Alt+Shift+J 를 사용하면 좀 더 다양한 양식을 활용할 수 있다.

 

Javadoc 양식은 이클립스 Window>Preferences>Java>Code Style>Code Templates 에서 설정할 수 있다.

 

 

골뱅이(@)가 붙는 태그는 아래와 같은 종류, 순서를 따른다.

클래스, 인터페이스, 메소드를 구분하니 적절하게 잘 사용해야겠다.

자세한 정보는 오라클 사이트에서 제공하고 있다. (http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html)

 

@author (classes and interfaces only, required)
@version (classes and interfaces only, required. See footnote 1)
@param (methods and constructors only)
@return (methods only)
@exception (@throws is a synonym added in Javadoc 1.2)
@see
@since
@serial (or @serialField or @serialData)
@deprecated (see How and When To Deprecate APIs)

 

 

오라클에서 제공하는 예제

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
 * Graphics is the abstract base class for all graphics contexts
 * which allow an application to draw onto components realized on
 * various devices or onto off-screen images.
 * A Graphics object encapsulates the state information needed
 * for the various rendering operations that Java supports.  This
 * state information includes:
 * <ul>
 * <li>The Component to draw on
 * <li>A translation origin for rendering and clipping coordinates
 * <li>The current clip
 * <li>The current color
 * <li>The current font
 * <li>The current logical pixel operation function (XOR or Paint)
 * <li>The current XOR alternation color
 *     (see <a href="#setXORMode">setXORMode</a>)
 * </ul>
 * <p>
 * Coordinates are infinitely thin and lie between the pixels of the
 * output device.
 * Operations which draw the outline of a figure operate by traversing
 * along the infinitely thin path with a pixel-sized pen that hangs
 * down and to the right of the anchor point on the path.
 * Operations which fill a figure operate by filling the interior
 * of the infinitely thin path.
 * Operations which render horizontal text render the ascending
 * portion of the characters entirely above the baseline coordinate.
 * <p>
 * Some important points to consider are that drawing a figure that
 * covers a given rectangle will occupy one extra row of pixels on
 * the right and bottom edges compared to filling a figure that is
 * bounded by that same rectangle.
 * Also, drawing a horizontal line along the same y coordinate as
 * the baseline of a line of text will draw the line entirely below
 * the text except for any descenders.
 * Both of these properties are due to the pen hanging down and to
 * the right from the path that it traverses.
 * <p>
 * All coordinates which appear as arguments to the methods of this
 * Graphics object are considered relative to the translation origin
 * of this Graphics object prior to the invocation of the method.
 * All rendering operations modify only pixels which lie within the
 * area bounded by both the current clip of the graphics context
 * and the extents of the Component used to create the Graphics object.
 * 
 * @author      Sami Shaio
 * @author      Arthur van Hoff
 * @version     %I%, %G%
 * @since       1.0
 */
public abstract class Graphics {
 
    /** 
     * Draws as much of the specified image as is currently available
     * with its northwest corner at the specified coordinate (x, y).
     * This method will return immediately in all cases, even if the
     * entire image has not yet been scaled, dithered and converted
     * for the current output device.
     * <p>
     * If the current output representation is not yet complete then
     * the method will return false and the indicated 
     * {@link ImageObserver} object will be notified as the
     * conversion process progresses.
     *
     * @param img       the image to be drawn
     * @param x         the x-coordinate of the northwest corner
     *                  of the destination rectangle in pixels
     * @param y         the y-coordinate of the northwest corner
     *                  of the destination rectangle in pixels
     * @param observer  the image observer to be notified as more
     *                  of the image is converted.  May be 
     *                  <code>null</code>
     * @return          <code>true</code> if the image is completely 
     *                  loaded and was painted successfully; 
     *                  <code>false</code> otherwise.
     * @see             Image
     * @see             ImageObserver
     * @since           1.0
     */
    public abstract boolean drawImage(Image img, int x, int y, 
                                      ImageObserver observer);
 
 
    /**
     * Dispose of the system resources used by this graphics context.
     * The Graphics context cannot be used after being disposed of.
     * While the finalization process of the garbage collector will
     * also dispose of the same system resources, due to the number
     * of Graphics objects that can be created in short time frames
     * it is preferable to manually free the associated resources
     * using this method rather than to rely on a finalization
     * process which may not happen for a long period of time.
     * <p>
     * Graphics objects which are provided as arguments to the paint
     * and update methods of Components are automatically disposed
     * by the system when those methods return.  Programmers should,
     * for efficiency, call the dispose method when finished using
     * a Graphics object only if it was created directly from a
     * Component or another Graphics object.
     *
     * @see       #create(int, int, int, int)
     * @see       #finalize()
     * @see       Component#getGraphics()
     * @see       Component#paint(Graphics)
     * @see       Component#update(Graphics)
     * @since     1.0
     */
    public abstract void dispose();
 
    /**
     * Disposes of this graphics context once it is no longer 
     * referenced.
     *
     * @see       #dispose()
     * @since     1.0
     */
    public void finalize() {
        dispose();
    }
}
cs

 

 

참고

Javadoc Tool

http://www.oracle.com/technetwork/java/javase/documentation/index-jsp-135444.html

http://devist.tistory.com/112

 

자바 공백 검수 쉽게 하기

공백 검수를 .equals("") 나 != null 식으로 했는데, 좀 더 진화된 방법이 있었다.

 

공백 검수 잘못된 예

1
2
3
    if (!comfile.equals("") && comfile != null) {
        paramMap.put("companyImageUrl", comIdx+".jpg");        
    }
cs

위처럼 쓸 경우, comfile 파라미터 자체가 null 일 경우 if문 수행할 때 오류가 난다.

파라미터 자체가 null 일 수 없기 때문.

쉽게말하면,

null.equals("") → X
"".equals("") → O

따라서 아래와 같이 StringUtils 의 isEmpty() 메소드를 사용하도록.

 

공백 검수 방법 (StringUtils.isEmpty 메소드 사용)

1
2
3
    if (!StringUtils.isEmpty(company.getCompanyImage())) {
        paramMap.put("companyImageUrl", company.getCompanyCode()+".jpg");        
    }
cs


활용 예)

1
double preLat = Double.parseDouble(StringUtils.isEmpty(param.get("preLat")) ? "0" : param.get("preLat").toString());
cs

 

 

<StringUtils.isEmaty 메소드>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    /**
     * Check whether the given {@code String} is empty.
     * <p>This method accepts any Object as an argument, comparing it to
     * {@code null} and the empty String. As a consequence, this method
     * will never return {@code true} for a non-null non-String object.
     * <p>The Object signature is useful for general attribute handling code
     * that commonly deals with Strings but generally has to iterate over
     * Objects since attributes may e.g. be primitive value objects as well.
     * @param str the candidate String
     * @since 3.2.1
     */
    public static boolean isEmpty(Object str) {
        return (str == null || "".equals(str));
    }
cs


Java 개발환경 설정 (Java 프로그램 실행 환경 이해하기)

JDK는 무엇이고 왜 설치해야 하는 것인지, 자바 개발은 어떤 환경일 때 가능한 것인지 까먹지 않기 위해 학원 실습 내용과 방통대 수업내용을 취합해서 정리해보았다.

 

Java 프로그램의 실행

1. 자바소스 Hello.java 는 컴파일러를 통해 바이트코드 Hello.class 로 컴파일되며,

2. 바이트코드 Hello.class 는 각 운영체제의 자바플랫폼 JVM(Java Virtual Machine)을 통해 자바 애플리케이션으로 실행된다.

※ 애플리케이션 : Java 플랫폼에서 바로 실행되는 프로그램
※ 애플릿 : HTML 웹페이지에 포함되어 있는 자바프로그램. 브라우저 내에서 애플릿을 실행한다.

 

<Java 프로그램의 실행>

 Java 소스
Hello.java

컴파일러

 →

바이트코드[각주:1]
Hello.class

 

 

 

 

 

 ↙↓↘

 

 

 

 

Sun 시스템
자바플랫폼
JVM

 Windows 시스템
자바플랫폼
JVM

 Mac 시스템
자바플랫폼
JVM

 

 

  ↓

 

 

 

Java 애플리케이션
바로 실행

Java 애플리케이션
바로 실행

 Java 애플리케이션
바로 실행

 

요약 : 컴파일된 자바소스는 각 운영체제에 설치되어 있는 자바플랫폼을 통해 실행된다.

→ 자바소스를 실행시키려면 자바 플랫폼이 설치되어 있어야 한다.

 

Java 플랫폼

자바 프로그램의 실행을 위한 하드웨어와 소프트웨어 환경.

Java 플랫폼은 Java 프로그램이 동작하기 위한 소프트웨어 플랫폼으로, 각각의 운영체제에 맞는 Java 플랫폼을 설치해야 한다.

 

 

 

 

 

 

Java 프로그램

 

   

 

 

 C 프로그램

 

 Java 플랫폼

   

 

 운영체제 (Windows 등)

 

 컴퓨터 시스템 (Hardware)

※ C프로그램은 운영체제에서 바로 컴파일

 

 Java 플랫폼의 구성

 Java VM (Virtual Machine)

Java API (Application Programming Interface)

 - 자바 가상 기계
 - 자바 프로그램의 구동엔진
 - 실행에 필요한 사항을 관리
 - Garbage Collection : 자동으로 메모리 정리

 - 프로그램 개발에 필요한 각종 라이브러리
 - 패키지들이 계층구조로 분류되어 있음. ex) java.lang, java.util, 등등
 - 기본API, 확장 API

 

요약 : 자바 플랫폼은 각 운영체제에 맞는 것을 설치해야 한다.

설치파일 다운로드 방법 : Java SDK (Java Software Development Kit) (JDK라고도 함) 은 오라클 홈페이지에서 제공한다.

 

Java 프로그래밍을 위한 준비 작업

1. Java SDK 다운로드

※ Java Standard Edition Development Kit (JDK)

자바개발을 위해서는 자바플랫폼 환경이 구축되어있어야 하므로 JDK 를 설치하도록 한다.

-구글에 JDK download 키워드로 검색해도 되고
-오라클 홈페이지 Java SE 카테고리 > Downloads 탭에 직접 들어가도 됨 (아래 링크 참고)

Oracle Technology Network > Java > Java SE > Downloads
http://www.oracle.com/technetwork/java/javase/downloads/index.html

 

다운로드 파일 종류는 JDK, Server JRE, JRE 3가지가 있는데 개발자용인 JDK를 다운로드 한다.

* JDK : Java 개발 도구
* JRE : 자바 실행 환경

 

Java SE Development Kit 8u91를 다운로드한다. (2016.05.08 기준)

운영체제 : Windows x64
파일명 : jdk-8u91-windows-x64.exe

(※ 오라클 로그인 하고 라이센스 동의 해야 함)

 

설치하면 jdk, jre 폴더가 자동으로 생긴다.

* jdk 폴더 : 개발할 수 있는 라이브러리
* jrd 폴더 : 실행할 수 있는 파일이 있음

 

2. Java API 문서 (참고용)

API 문서는 자바 기술문서로 자바개발 시 참고하면 유용하다.

 

<자바 JDK8 API 문서 링크>
http://docs.oracle.com/javase/8/docs/api/index.html

 

또는 오라클 홈페이지에서 찾아 들어가는 방법이 있다.

Oracle Technology Network > Java > Java SE > Documentation 
http://www.oracle.com/technetwork/java/javase/documentation/index.html

 

Documentation 탭에 들어간 후

 Reference 카테고리의 Java SE API Documentation 링크를 클릭하면 된다.

 

 

 

 

3. 환경변수 설정

원래는 자바설치폴더인 jdk폴더 내 bin폴더까지 경로이동해야 javac 커맨더 입력이 성공하는데, 환경변수 path에 bin 경로 추가하면 커맨더창 아무 디렉토리에서나 javac 커맨더가 성공한다.

 

변수 Path 에 jdk bin 폴더 경로를 변수 값에 추가한다.

 

 

커맨더창에 javac 명령어 입력했을 때 아래와 같이 뜨면 성공이다.

 

※ 자바파일 컴파일하는 명령어 :  javac '클래스파일명.확장자'

※ 컴파일된 클래스파일 실행하는 명령어 : java '클래스파일명' (.class 붙이지 않는다)

그 다음에는 변수 CLASSPATH 를 만들고 .; 을 변수값으로 한다.

변수값 .(점)은 현재 폴더에 있는 클래스를 사용할 수 있다는 의미이고, 컴파일러는 CLASSPATH에 지정된 경로에서 클래스를 찾는다.

 

 

4. Java 개발 도구 (IDE) 다운로드. ex) Eclipse 등

http://www.eclipse.org/downloads/

최신버전이어도 상관없다.
Eclipse IDE for Java EE Developers 다운로드

New>Java Project 가 없으면 'Open Perspective'에서 'Java' 선택한다.

 

 

 

이클립스 테마 등 개인 취향을 바탕으로 세팅 마치면 자바 개발 환경은 이제 다 갖춰진 것이다.

 

 

 

 

 

  1. -Java 소스를 컴파일한 결과물 -확장자는 .class -클래스파일이라고도 함 -Java플랫폼에서 실행가능한 중간코드 [본문으로]

+ Recent posts