1. 변수의 개념


프로그램이 작업을 처리하는 과정에서 필요에 따라 데이터를 메모리에 저장합니다.


이때 변수를 사용하는데 변수란(Variable) 값을 저장할 수 있는 메모리 공간을 의미 합니다.


이름이 변수인 이유는 수시로 값이 변동될 수 있기 때문이고, 변수엔 단 하나의 값만 저장이 가능합니다.



2. 변수의 선언


int          number;  //정수(int)값을 저장할 수 있는 number변수 선언.

double   percent;  //실수(double)값을 저장할 수 있는 percent변수 선언.


변수의 타입이 다를 경우 각각 선언해 주어도 되지만, 같을 경우엔 한번에 선언을 해도 됩니다.


ex) int number, number1, number2;


또한, 변수의 이름을 정할때엔 규칙이 있습니다.


작성규칙 

예시 

첫번째 글자는 문자이거나 '$'(달러) 혹은 '_'(언더바) 여야되고 숫자로 시작할 수 없습니다. (필수)

가능한 것들 : happy,  _happy, $happy

불가능한 것들 : 100happy, *happy, ^^happy

영어의 대소문자가 구분됩니다.(필수)

filename과 fileName은 다른변수 취급 

첫 문자는 영어 소문자로 시작하고, 복합어의 두번째 시작문자는 대문자로 합니다. (관례) 

filename -> fileName 

문자 수(길이)의 제한은 없습니다.

 

자바 예약어는 사용할 수 없습니다.(필수) 

 하단 표



분류 

예약어 

기본 데이터 타입 

boolean, byte, char, short, int, long, float, double 

접근 지정자 

private, protected, public 

클래스와 관련

class, abstract, interface, extends, implements, enum 

객체 관련

new, instanceof, this, super, null 

메서드 관련

void, return 

제어문 관련

if, else, switch, case, default, for, do, while, break, continue 

 논리값

true, false 

 예외 처리 관련

try, catch, finally, throw, throws

기타 

transient(직렬화하지 않음-선택적 직렬화), volatile(원자성보장), 

package(클래스 상단 패키지 선언), import(package import), 

synchronized(작업단위 동기화), 

native(타 언어로 구현된 기능 사용), 

final(변수를 상수화), 

static(직접 메모리 적재), 

strictfp(부동소수(floating point) 계산의 특정한(restrict) 사항들을 제어), 

assert(디버깅코드)














3. 변수값 저장


자바에서 변수값을 저장할 경우엔 '=' 연산자를 사용합니다. 수학에서의 '같다'라는 뜻은 '==' 연산자를 사용합니다. 좌측에 변수를 선언하고 '=' 연산자를 붙인 후 우측에 값을 지정하면 '좌측에 선언된 특정타입의 변수에 우측에 지정한 값을 저장한다'라는 뜻 입니다.


변수선언 예)

int number = 10;  //number라는 정수타입의 변수에 10이라는 값을 저장함.

 

같은 동작을 하는 다른 사용 예)

int number;     //number 라는 정수(int) 타입의 변수를 선언

number = 10;  //number 변수에 10이라는 값을 저장


변수의 초기값은 첫번째 선언의 예처럼 선언과 통시에 코드내에서 직접 입력하는 경우가 많고, 이것을 리터럴(literal)이라고 합니다. 의미상으로 리터럴(literal)은 상수(constant)와 같은 의미지만, 프로그램 상에서의 상수는 "값을 한번 정하면 변경할 수 없다"로 정의되기 때문에 구분을 위해 리터럴이라는 용어를 사용한다고 합니다.




이상 간단하지만 알아두면 도움이 될 변수관련 포스팅을 마치겠습니다.



Posted by Culinary developer

AND


정규표현식은 특정한 규칙을 가지는 문자를 표현하는데 사용하는 형식 언어로  


정규표현식을 자유 자재로 다룰 줄 알게 되면 상당한 시간을 단축할 수 있고, 


유용하며 코드가 깔끔해 집니다.


표현식

 설명 

 ^

 문자열의 시작

 문자열의 종료

 .

 임의의 한 문자 (문자의 종류 가리지 않음)

 단, \ 는 넣을 수 없음

 *

 앞 문자가 없을 수도 무한정 많을 수도 있음

 앞 문자가 하나 이상

 앞 문자가 없거나 하나있음

 []

 문자의 집합이나 범위를 나타내며 두 문자 사이는 - 기호로 범위를      나타낸다. []내에서 ^가 선행하여 존재하면 not 을 나타낸다.

 {}

 횟수 또는 범위를 나타낸다.

 ()

 소괄호 안의 문자를 하나의 문자로 인식 

 |

 패턴 안에서 or 연산을 수행할 때 사용

 \s

 공백 문자

 \S

 공백 문자가 아닌 나머지 문자

 \w

 알파벳이나 숫자

\W 

 알파벳이나 숫자를 제외한 문자

\d 

 숫자 [0-9]와 동일

\D 

 숫자를 제외한 모든 문자

 정규표현식 역슬래시(\)는 확장 문자
 역슬래시 다음에 일반 문자가 오면 특수문자로 취급하고 역슬래시 다음에 특수문자가 오면 그 문자 자체를 의미

(?i) 

 앞 부분에 (?i) 라는 옵션을 넣어주면 대소문자를 구분하지 않음



자바스크립트 또한 자바의 정규표현식과 비슷합니다.

아래 사용법만 익히면 쉽게 사용할 수 있습니다.

var filter = /[a-z]+/;

if (filter.test("a") == true) {

alert("success"); 

} else { 

alert("fail"); 

}



package regular;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.regex.Pattern;
import org.junit.Test;
/**
* @FileName : RegularTest.java
* @Project : test_project
* @Date : 2013. 5. 2.
* @작성자 : 이남규
* @프로그램설명 :
*/
public class RegularTest {
/**
* <pre>
* 문자열시작테스트 ^
*
* <pre>
*/
@Test
public void 문자열시작테스트() {
String regex = "^[a-zA-Z]{3}[0-9]+";
assertThat(true, is(matched(regex, "aAb09")));
assertThat(true, is(matched(regex, "aaa09")));
assertThat(true, is(matched(regex, "AAA09")));
assertThat(true, is(matched(regex, "zzZ09")));
assertThat(true, is(matched(regex, "zzZ00")));
assertThat(false, is(matched(regex, "zzZ")));
assertThat(false, is(matched(regex, "12a")));
assertThat(false, is(matched(regex, "aaaa09")));
}
/**
* <pre>
* 문자열의종료 $
*
* <pre>
*/
@Test
public void 문자열의종료() {
String regex = "a{2}$";
assertThat(true, is(matched(regex, "aa")));
assertThat(false, is(matched(regex, "aa11")));
}
/**
* <pre>
* 임의의한문자를나타냄 .
*
* <pre>
*/
@Test
public void 임의의한문자를나타냄() {
String regex = "aaa.bb";
assertThat(true, is(matched(regex, "aaa1bb")));
assertThat(true, is(matched(regex, "aaaCbb")));
assertThat(true, is(matched(regex, "aaaZbb")));
assertThat(true, is(matched(regex, "aaa!bb")));
assertThat(true, is(matched(regex, "aaa@bb")));
assertThat(true, is(matched(regex, "aaa#bb")));
assertThat(true, is(matched(regex, "aaa$bb")));
assertThat(true, is(matched(regex, "aaa%bb")));
assertThat(true, is(matched(regex, "aaa^bb")));
assertThat(true, is(matched(regex, "aaa&bb")));
assertThat(true, is(matched(regex, "aaa*bb")));
assertThat(true, is(matched(regex, "aaa(bb")));
assertThat(true, is(matched(regex, "aaa)bb")));
assertThat(true, is(matched(regex, "aaa-bb")));
assertThat(true, is(matched(regex, "aaa+bb")));
assertThat(true, is(matched(regex, "aaa=bb")));
assertThat(false, is(matched(regex, "aaabb")));
assertThat(false, is(matched(regex, "aaa\bb")));
assertThat(false, is(matched(regex, "aaa12bb")));
assertThat(false, is(matched(regex, "aaa$$bb")));
}
/**
* <pre>
* 앞문자가없을수도무한정있을수도있음 *
*
* <pre>
*/
@Test
public void 앞문자가없을수도무한정있을수도있음() {
String regex = "a*b";
assertThat(true, is(matched(regex, "ab")));
assertThat(true, is(matched(regex, "aaab")));
assertThat(true, is(matched(regex, "aab")));
assertThat(true, is(matched(regex, "b")));
assertThat(false, is(matched(regex, "aabb")));
assertThat(false, is(matched(regex, "aaccdd")));
assertThat(false, is(matched(regex, "a_ab")));
assertThat(false, is(matched(regex, "abcd")));
}
/**
* <pre>
* 앞문자가하나이상 +
*
* <pre>
*/
@Test
public void 앞문자가하나이상() {
String regex = "abc_A+";
assertThat(true, is(matched(regex, "abc_A")));
assertThat(true, is(matched(regex, "abc_AA")));
assertThat(true, is(matched(regex, "abc_AAA")));
assertThat(false, is(matched(regex, "abc")));
assertThat(false, is(matched(regex, "abc_")));
assertThat(false, is(matched(regex, "abc_AAb")));
assertThat(false, is(matched(regex, "abc_AA1")));
}
/**
* <pre>
* 앞문자가없거나하나있음 ?
*
* <pre>
*/
@Test
public void 앞문자가없거나하나있음() {
String regex = "abc_B?";
assertThat(true, is(matched(regex, "abc_")));
assertThat(true, is(matched(regex, "abc_B")));
assertThat(false, is(matched(regex, "abc_C")));
assertThat(false, is(matched(regex, "abc_DD")));
assertThat(false, is(matched(regex, "abc_11")));
}
/**
* <pre>
* 문자클래스지정1 []
*
* <pre>
*/
@Test
public void 문자클래스지정1() {
String regex = "[a-z0-9]";
assertThat(true, is(matched(regex, "a")));
assertThat(true, is(matched(regex, "b")));
assertThat(true, is(matched(regex, "z")));
assertThat(true, is(matched(regex, "0")));
assertThat(true, is(matched(regex, "8")));
assertThat(false, is(matched(regex, "A")));
assertThat(false, is(matched(regex, "aa")));
assertThat(false, is(matched(regex, "a0")));
assertThat(false, is(matched(regex, "00a")));
}
/**
* <pre>
* 문자클래스지정2 [^]
*
* <pre>
*/
@Test
public void 문자클래스지정2() {
String regex = "[^a-f1-3]";
assertThat(true, is(matched(regex, "g")));
assertThat(true, is(matched(regex, "h")));
assertThat(true, is(matched(regex, "4")));
assertThat(true, is(matched(regex, "0")));
assertThat(true, is(matched(regex, "9")));
assertThat(false, is(matched(regex, "a")));
assertThat(false, is(matched(regex, "2")));
}
/**
* <pre>
* 횟수또는범위1 {3}
* a 3개만 올 수 있음
*
* <pre>
*/
@Test
public void 횟수또는범위1() {
String regex = "a{3}b";
assertThat(true, is(matched(regex, "aaab")));
assertThat(false, is(matched(regex, "aab")));
assertThat(false, is(matched(regex, "aaaab")));
assertThat(false, is(matched(regex, "aaaaaaab")));
assertThat(false, is(matched(regex, "aaaaaaabb")));
}
/**
* <pre>
* 횟수또는범위2 {3,}
* a 3개 이상 올 수 있음
* <pre>
*/
@Test
public void 횟수또는범위2() {
String regex = "a{3,}b";
assertThat(true, is(matched(regex, "aaab")));
assertThat(true, is(matched(regex, "aaaab")));
assertThat(true, is(matched(regex, "aaaaab")));
assertThat(true, is(matched(regex, "aaaaaaaaaaaaaaaaaaaaaaaaab")));
assertThat(false, is(matched(regex, "aab")));
assertThat(false, is(matched(regex, "ab")));
assertThat(false, is(matched(regex, "b")));
}
/**
* <pre>
* 횟수또는범위3 {3,5}
* a 3개 이상 5개 이하 올 수 있음
* <pre>
*/
@Test
public void 횟수또는범위3() {
String regex = "a{3,5}b";
assertThat(true, is(matched(regex, "aaab")));
assertThat(true, is(matched(regex, "aaaab")));
assertThat(true, is(matched(regex, "aaaaab")));
assertThat(false, is(matched(regex, "aaaaaab")));
assertThat(false, is(matched(regex, "aaaaaaaaaaab")));
String regex1 = "a{3,5}.";
assertThat(true, is(matched(regex1, "aaab")));
assertThat(false, is(matched(regex1, "aaabb")));
String regex2 = "a{3,5}.{4}";
assertThat(true, is(matched(regex2, "aaabbbb")));
assertThat(false, is(matched(regex2, "aaabbbbb")));
assertThat(false, is(matched(regex2, "aaab")));
assertThat(false, is(matched(regex2, "aaabb")));
assertThat(false, is(matched(regex2, "aaabbb")));
}
/**
* <pre>
* 소괄호문자를하나의문자로인식 ()
*
* <pre>
*/
@Test
public void 소괄호문자를하나의문자로인식() {
String regex = "abc(11){2}";
assertThat(true, is(matched(regex, "abc1111")));
assertThat(false, is(matched(regex, "abc11")));
assertThat(false, is(matched(regex, "ab11")));
assertThat(false, is(matched(regex, "ab111111")));
}
/**
* <pre>
* or연산1 |
*
* <pre>
*/
@Test
public void or연산() {
String regex = "hello|world";
assertThat(true, is(matched(regex, "hello")));
assertThat(true, is(matched(regex, "world")));
assertThat(false, is(matched(regex, "helloworld")));
assertThat(false, is(matched(regex, "hello|world")));
String regex1 = "(hello|world){1}";
assertThat(true, is(matched(regex1, "hello")));
assertThat(true, is(matched(regex1, "world")));
assertThat(false, is(matched(regex1, "helloworld")));
}
/**
* <pre>
* 알파벳이나숫자 \w
*
* <pre>
*/
@Test
public void 알파벳이나숫자() {
String regex = "\\w";
assertThat(true, is(matched(regex, "a")));
assertThat(true, is(matched(regex, "Z")));
assertThat(true, is(matched(regex, "4")));
assertThat(false, is(matched(regex, "$")));
assertThat(false, is(matched(regex, "")));
assertThat(false, is(matched(regex, "12")));
}
/**
* <pre>
* 알파벳이나숫자를제외한문자 \W
*
* <pre>
*/
@Test
public void 알파벳이나숫자를제외한문자() {
String regex = "\\W";
assertThat(true, is(matched(regex, "@")));
assertThat(true, is(matched(regex, ")")));
assertThat(true, is(matched(regex, "\\")));
assertThat(false, is(matched(regex, "1")));
assertThat(false, is(matched(regex, "a")));
String regex1 = "\\W{3}";
assertThat(true, is(matched(regex1, "!@#")));
assertThat(true, is(matched(regex1, ")(*")));
}
/**
* <pre>
* 숫자만 \d
*
* <pre>
*/
@Test
public void 숫자만() {
String regex = "\\d";
assertThat(true, is(matched(regex, "1")));
assertThat(true, is(matched(regex, "3")));
assertThat(true, is(matched(regex, "4")));
assertThat(false, is(matched(regex, "a")));
assertThat(false, is(matched(regex, "Z")));
assertThat(false, is(matched(regex, "11")));
}
/**
* <pre>
* 숫자를제외한모든문자 \\D
*
* <pre>
*/
@Test
public void 숫자를제외한모든문자() {
String regex = "\\D";
assertThat(true, is(matched(regex, "a")));
assertThat(true, is(matched(regex, "")));
assertThat(true, is(matched(regex, "")));
assertThat(false, is(matched(regex, "1")));
assertThat(false, is(matched(regex, "3")));
assertThat(false, is(matched(regex, "44")));
}
/**
* <pre>
* 역슬래스테스트 \
*
* <pre>
*/
@Test
public void 역슬래스테스트() {
String regex = "a\\sb";
assertThat(true, is(matched(regex, "a b")));
String regex1 = "a\\tb";
assertThat(true, is(matched(regex1, "a b")));
String regex2 = "a\\nb";
assertThat(true, is(matched(regex2, "a\nb")));
}
/**
* <pre>
* 대소문자구분안함 (?i)
*
* <pre>
*/
@Test
public void 대소문자구분안함() {
String regex = "(?i)abc";
assertThat(true, is(matched(regex, "abc")));
assertThat(true, is(matched(regex, "ABC")));
assertThat(true, is(matched(regex, "aBc")));
String regex1 = "abc";
assertThat(false, is(matched(regex1, "ABC")));
assertThat(false, is(matched(regex1, "abC")));
assertThat(false, is(matched(regex1, "aBc")));
}
@Test
public void 특수문자테스트() {
String regex = "^[a-z0-9A-Z]*@#";
assertThat(true, is(matched(regex, "12@#")));
}
/**
* <pre>
* 영어숫자만
*
* <pre>
*/
@Test
public void 영어숫자만() {
String regex = "^[0-9a-zA-Z]*$";
assertThat(true, is(matched(regex, "1212dafda")));
assertThat(true, is(matched(regex, "1")));
assertThat(true, is(matched(regex, "a")));
assertThat(true, is(matched(regex, "Z")));
assertThat(true, is(matched(regex, "")));
assertThat(false, is(matched(regex, "")));
}
/**
* <pre>
* 한글만
*
* <pre>
*/
@Test
public void 한글만() {
String regex = "^[가-힣]*$";
assertThat(true, is(matched(regex, "")));
assertThat(true, is(matched(regex, "가나다")));
assertThat(true, is(matched(regex, "가나다라하햐호호유")));
assertThat(true, is(matched(regex, "")));
assertThat(true, is(matched(regex, "")));
assertThat(false, is(matched(regex, "1")));
assertThat(false, is(matched(regex, "a")));
assertThat(false, is(matched(regex, "Z")));
}
/**
* <pre>
* replaceAllTest
* 한글 삭제
* <pre>
*/
@Test
public void replaceAllTest() {
String value = "abc한123";
String hangulDeleteValue = value.replaceAll("[가-힣]*", "");
assertThat(true, is(matched(hangulDeleteValue, "abc123")));
}
/**
* <pre>
* 이메일체크
*
* <pre>
*/
@Test
public void 이메일체크() {
String emailRegex = "^[a-z0-9A-Z_-]*@[a-z0-9A-Z]*.[a-zA-Z.]*$";
assertThat(true, is(matched(emailRegex, "lng1982@naver.com")));
assertThat(true, is(matched(emailRegex, "lng1982@naver.co.kr")));
assertThat(true, is(matched(emailRegex, "lng1982@daum.net")));
assertThat(true, is(matched(emailRegex, "lng1982@test.org")));
assertThat(false, is(matched(emailRegex, "lng1982$@naver.com")));
assertThat(false, is(matched(emailRegex, "lng1982naver.com")));
assertThat(false, is(matched(emailRegex, "lng1982naver.com12")));
}
/**
* <pre>
* 휴대폰체크
*
* <pre>
*/
@Test
public void 휴대폰체크() {
String phoneRegex = "^0\\d{2}";
assertThat(true, is(matched(phoneRegex, "010")));
assertThat(true, is(matched(phoneRegex, "011")));
assertThat(true, is(matched(phoneRegex, "019")));
assertThat(false, is(matched(phoneRegex, "111")));
assertThat(false, is(matched(phoneRegex, "11a")));
String phoneRegex1 = "^0\\d{2}\\d{3,4}";
assertThat(true, is(matched(phoneRegex1, "010866")));
assertThat(true, is(matched(phoneRegex1, "0108667")));
assertThat(false, is(matched(phoneRegex1, "01086677")));
assertThat(false, is(matched(phoneRegex1, "010866771")));
String phoneRegex2 = "^0\\d{2}\\d{3,4}\\d{4}$";
assertThat(true, is(matched(phoneRegex2, "01086677100")));
assertThat(true, is(matched(phoneRegex2, "01086677101")));
assertThat(true, is(matched(phoneRegex2, "0108667710")));
assertThat(false, is(matched(phoneRegex2, "010866771000")));
assertThat(false, is(matched(phoneRegex2, "01086677100a")));
assertThat(false, is(matched(phoneRegex2, "11086677100a")));
}
/**
* <pre>
* 주민등록번호
*
* <pre>
*/
@Test
public void 주민등록번호() {
String regex = "^\\d{6}(1|2|3|4)";
assertThat(true, is(matched(regex, "8210111")));
assertThat(true, is(matched(regex, "8210112")));
assertThat(true, is(matched(regex, "8210113")));
assertThat(true, is(matched(regex, "8210114")));
assertThat(false, is(matched(regex, "8210115")));
assertThat(false, is(matched(regex, "82101151")));
String regex1 = "^\\d{6}(1|2|3|4)\\d{6}$";
assertThat(true, is(matched(regex1, "8210201111111")));
assertThat(true, is(matched(regex1, "8210202222222")));
assertThat(true, is(matched(regex1, "8210203333333")));
assertThat(true, is(matched(regex1, "8210204444444")));
assertThat(false, is(matched(regex1, "8210205555555")));
assertThat(false, is(matched(regex1, "82102055555551")));
assertThat(false, is(matched(regex1, "8210205a55551")));
assertThat(false, is(matched(regex1, "8210205\55551")));
String regex2 = "^\\d{6}[1-4]\\d{6}$";
assertThat(true, is(matched(regex2, "8210201111111")));
assertThat(true, is(matched(regex2, "8210202111111")));
assertThat(true, is(matched(regex2, "8210203111111")));
assertThat(true, is(matched(regex2, "8210204111111")));
}
/**
* <pre>
* 아이피체크
*
* <pre>
*/
@Test
public void 아이피체크() {
String regex = "^\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}$";
assertThat(true, is(matched(regex, "172.18.167.92")));
assertThat(true, is(matched(regex, "172.181.167.921")));
assertThat(true, is(matched(regex, "1.181.167.921")));
assertThat(true, is(matched(regex, "1.1.167.921")));
assertThat(true, is(matched(regex, "1.1.7.921")));
assertThat(true, is(matched(regex, "1.1.7.9")));
assertThat(false, is(matched(regex, "1721.181.167.921")));
assertThat(false, is(matched(regex, "172.1811.167.921")));
assertThat(false, is(matched(regex, "172.181.1671.921")));
assertThat(false, is(matched(regex, "172.181.167.9211")));
}
/**
* <pre>
* 파일확장자체크
*
* <pre>
*/
@Test
public void 파일확장자체크() {
String regex = "^\\S+.(?i)(png|jpg|bmp|gif)$";
assertThat(true, is(matched(regex, "test.png")));
assertThat(true, is(matched(regex, "test.jpg")));
assertThat(true, is(matched(regex, "test.bmp")));
assertThat(true, is(matched(regex, "test.gif")));
assertThat(true, is(matched(regex, "test1#$adf한.gif")));
assertThat(true, is(matched(regex, "test.GIF")));
assertThat(true, is(matched(regex, "test.JPG")));
assertThat(true, is(matched(regex, "test.BMP")));
assertThat(true, is(matched(regex, "test.PNG")));
assertThat(true, is(matched(regex, "testA.PNG")));
assertThat(false, is(matched(regex, "test a.gif")));
assertThat(false, is(matched(regex, "test a.jpg")));
}
@Test
public void 비밀번호체크() {
String regex = "^[a-zA-Z0-9~!@#$%^&*()]{8,16}";
assertThat(true, is(matched(regex, "adfadf1212")));
assertThat(true, is(matched(regex, "a23d3f31")));
assertThat(true, is(matched(regex, "rbdn200111111111")));
assertThat(true, is(matched(regex, "aaaaaaaaaa212121")));
assertThat(true, is(matched(regex, "aBdAf1234")));
assertThat(true, is(matched(regex, "abc~!@#$234")));
assertThat(true, is(matched(regex, "~!@#$%^&*()")));
assertThat(true, is(matched(regex, "1asfdA~!@af^&*()")));
assertThat(false, is(matched(regex, "a")));
assertThat(false, is(matched(regex, "a121212")));
assertThat(false, is(matched(regex, "a121212a121212a121212")));
}
@Test
public void 비밀번호체크2() {
String regex = "^([a-zA-Z]+[0-9]+[~!@#$%^&*()]+)";
assertThat(true, is(matched(regex, "a0@")));
assertThat(false, is(matched(regex, "a@")));
assertThat(false, is(matched(regex, "@1")));
}
/**
* <pre>
* groupingTest
* hello kyu world 문자열을 hello namkyu world 로 바꾸기
* 간단하게 hello와 world를 그룹으로 지정하기 위해서 괄호로 묶어서 아래와 같이 처리
* <pre>
*/
@Test
public void groupingTest() {
String result = "hello kyu world".replaceAll("(hello) kyu (world)", "$1 namkyu $2");
assertThat("hello namkyu world", is(result));
}
/**
* <pre>
* nonGroupingTest
* ?: <-- 이 문자열이 non grouping 문자
* hello kyu world 문자열에서 양쪽의 hello, world를 삭제한 kyu만 출력
* <pre>
*/
@Test
public void nonGroupingTest() {
String result = "hello kyu world".replaceAll("(?:hello) (kyu) (?:world)", "$1");
assertThat("kyu", is(result));
}
/**
* <pre>
* matched
*
* <pre>
* @param regex
* @param inputTxt
* @return
*/
private boolean matched(String regex, String inputTxt) {
return Pattern.matches(regex, inputTxt);
}


자료출처 http://lng1982.tistory.com/141



Posted by Culinary developer

AND


Slf4j를 직접 사용하는 경우, 혹은 slf4j를 사용하는 라이브러리를 사용하는 경우 다음과 같은 에러가 발생할 경우가 있다. 


log4j:WARN No appenders could be found for logger (org.eclipse.jetty.util.log).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.



이 경우엔 다음의 코드를 프로그램이 실행되는 메인 메서드에 삽입해주면 간단하게 해결된다.

물론 경우에 따라 라이브러리를 등록해야 해결되는 경우도 있음...^^


BasicConfigurator.configure();



Posted by Culinary developer

AND


자바에서 링크로 파일을 다운로드 받아야 하는 경우가 있다. 

그럴경우 간단한 방법이 있다.

 
 
try{
	java.net.URL downLink = new java.net.URL("다운로드링크 지정-input downloadLink(String type)");
	java.nio.channels.ReadableByteChannel rbc = java.nio.channels.Channels.newChannel(downLink.openStream());
	java.io.FileOutputStream outputStream = new java.io.FileOutputStream("파일명.확장자(ex.fileName.txt)");
	outputStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
				
}catch(java.io.IOException e){
		e.printStackTrace();
}




posted by Culinary developer

AND



Iterable<> 타입을 List<> 타입으로 형변환 하는 법은 굳이 반복문을 돌리지 않아도 되는 두가지 방법이 있다. 


 첫번째 방법
import com.google.common.collect.Lists;



Iterator<> myIterator = ... //some iterator

List<> myList = Lists.newArrayList(myIterator);


두번째 방법 
import org.apache.commons.collections.IteratorUtils;



Iterator<> myIterator = ...//some iterator

List<> myList = IteratorUtils.toList(myIterator); 


posted by Culinary developer



AND


먼저 spring boot project를 생성한다. 
나의 경우엔 jar, maven 으로 해주었음. gradle프로젝트도 동일함. 
프로젝트를 생성하면 기본적으로 어플리케이션이 생성된다. 



다음 컨트롤러를 만들어준다. 
컨트롤러는 그냥 클래스를 생성한 후 어노테이션으로 컨트롤러만 지정해주면 되고 추가적으로 접속테스트를 위한 리퀘스트 맵핑을 지정해준다. 




다음으로 src > main 이 기본으로 생성되는 폴더인데, 하위에 webapp을 생성, 하위로 view폴더를 생성 하여 testView.jsp를 만들어 준다. 




jsp파일엔 맵핑이 제대로 된 경우 확인 할 수 있을 정도의 문구를 넣어준다. 다음으로 프로젝트를 구동시킨다. 




인터넷 브라우저에서 입력한 주소에 접속하면 역시나 에러가 발생한다. 뷰리졸버를 dependency에 추가해 주지 않아서 발생하는 에러이다. 





보통 검색을 해보면 spring boot 에서 view mapping을 해주기 위해선 embeded-tomcat jasper를 dependency에 추가하고 resource > application.property파일에 다음과 같이 등록해주면 해결된다는 말이 많다.




하지만 나 같은경우엔 등록해 주어도 여전히 맵핑이 되지 않아서 고생을 좀 했다. 이건 maven에서도 gradle에서도 마찬가지 였다.



404에러다... 그러다가 다음과 같은 방법으로 bean을 등록해주면 가능하다는 것을 알게되었다. application.java 클래스를 다음과 같이 수정해 주면 에러는 해결된다. 



수정전 application.java
package com.example;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class DemoApplication {


	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}
수정 후 application.java

package com.example;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.InternalResourceViewResolver;


@ComponentScan
@Configuration
@EnableAutoConfiguration
public class DemoApplication {


    public static void main(String[] args) {
	SpringApplication.run(DemoApplication.class, args);
    }

	

    @Bean
    public InternalResourceViewResolver setupViewResolver() {

        InternalResourceViewResolver resolver = new InternalResourceV        iewResolver();

        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}


다시 spring boot application을 run 시키고 브라우저에 접속해 보면 다음과 같이 뷰가 맵핑된 것을 확인 할 수 있다. 

spring boot 다양한 sample 모음 :

 posted by Culinary developer



AND




스프링 boot프로젝트를 구동시킬 때 다음과 같은 에러가 발생해서 고생을 좀 했습니다. 스프링부츠 생성시 JPA로 사용할 데이터베이스를 선택하지 않아서 의존관계 주입시 에러가 발생하는 것으로 보여졌습니다. 해결방법은 의외로 간단했습니다. 프로젝트의 pom.xml파일에 의존관계에



    com.h2database
    h2
    1.3.156

해당 코드를 추가해 주니 간단하게 해결되었습니다. 

 이상으로 포스팅을 마치겠습니다 

 Posted by Culinary developer



AND


제가 오늘 접하게 된 "could not write file .classpath" 해결 건에 대해서 포스팅 해보도록 하겠습니다.



프로젝트를 진행 하던 중 maven을 지원하지 않아 jar 파일을 직접 추가하려던중.....




이와 같은 에러를 발견하였습니다. 



정확한 에러내용은

'Setting build path' has encountered a problem.

Could not write file:

C:\Programming\workspace(sts3.7)\WebProject1\.classpath.

C:\Programming\workspace(sts3.7)\WebProject1\.classpath (액세스가 거부되었습니다) 

이었습니다..


구글링을 해보니 프로젝트를 import 할 경우 다른 pc에서 생성된 프로젝트는 .classpath파일과 .project파일이 숨김표시가 될 수도 있다는 것을 알 수 있었습니다.



아주 간단한 해결방법을 설명하도록 하겠습니다.

우선 폴더의 상단에 보기탭을 클릭 후 가장 우측의 옵션을 클릭하시면 폴더 옵션으로 진입 하실 수 있습니다.

(window 8.1 기준)



폴더옵션에서 상단의 보기 탭을 클릭 후 숨김파일, 폴더, 드라이브 보기를 체크하고 적용 후 확인을 해줍니다.



그 다음 sts workspace로 지정된 폴더에서 해당 프로젝트폴더를 찾아 들어갑니다.

들어가면 그림과 같이 .classpath 파일에 워터마크 효과가 들어가서 반투명으로 보이는 것을 확인할 수

 있습니다.


.classpath 파일의 특성에 숨김 체크박스를 해지해 주시고 적용, 확인을 눌러 주시면 됩니다.


물론 다른 이유에서 같은 에러가 발생할 가능성도 있지만 저의 경우에는 이것으로 해결되었습니다.


이상으로 포스팅을 마치도록 하겠습니다.


Posted by Culinary developer

AND


이번에는 해당 위치에 폴더가 없을 경우 지정해준 디렉토리에 맞게 


자동으로 폴더를 생성해주는 exists() 메서드를 포스팅 하겠습니다.


예제의 경우엔 C드라이브 하위에 Test란 폴더를 미리 생성해 두고 하위로 file이란 폴더를 생성하는 방식으로 


진행하도록 하겠습니다.



그림을 보시면 Test란 폴더의 하위엔 아무런 폴더가 없습니다.



*code

import java.io.File;

public class CreateFileDirectoryTest {

	//메인 메서드 실행
	public static void main(String[] args) {
		
		//생성할 파일경로 지정
		String path = "c://test//file.txt";
		//파일 객체 생성
		File file = new File(path);
		//!표를 붙여주어 파일이 존재하지 않는 경우의 조건을 걸어줌
		if(!file.exists()){
			//디렉토리 생성 메서드
			file.mkdirs();
			System.out.println("created directory successfully!");
		}
	}
}
}



메서드를 실행시키니 성공적으로 디렉토리가 생성되었다는 문자열이 콘솔창에 찍히는 것을 확인 할 수 있습니다.


*result



다시 Test파일을 보니 file이란 폴더가 생성된 것을 확인하실 수 있습니다.


이상으로 폴더 디렉토리 생성에 관한 포스팅을 마치도록 하겠습니다.

Posted by Culinary developer


AND

이번 포스팅은 초간단 split 메서드를 이용해서 string 문자열을 잘라 배열에 담는법을 소개하려고 합니다. 


split메서드는 split("")에서 큰따옴표("")안의 문자를 기준으로 문자열을 잘라서 배열에 담아주는 녀석으로 

예를들어 "다음,네이버,구글,인터넷"이라는 문자열이 있을때 ,를 기준으로 나누고 싶다면 

문자열.split(",")의 방식으로 지정해 주면 됩니다. 샘플코드 및 결과 값은 아래와 같습니다. 


 *샘플코드 (sample code)
package com.ujin.test;

import java.util.Arrays;

public class StringTest {

	//메인 메서드로 실행
	public static void main(String[] args) {
		
		StringTest st = new StringTest();
		st.splitTest();
		
	}
	
	
	//split메서드를 이용해서 스트링 문자열 자르기 sample	 
	public void splitTest(){
		
		//String 문자열 생성
		String testStr = "다음,네이버,구글,인터넷";
		
		//split 메서드안에 잘라줄 기준이 되는 문자 입력
		String[] testArr = testStr.split(",");
		
		//결과 값 콘솔출력
		System.out.println(Arrays.deepToString(testArr));
	}
}


*콘솔 결과창 (console result)


이상으로 포스팅을 마치겠습니다.


Posted by Culinary developer





AND