Map null값 체크 //collections4 compile "org.apache.commons:commons-collections4:4.0" MapUtils를 사용하여 map 객체의 null 체크가 가능하다. Map map = new HashMap; MapUtils.isEmpty(map); MapUtils.isEmpty() /** * Null-safe check if the specified map is empty. * * Null returns true. * * @param map the map to check, may be null * @return true if empty or null * @since 3.2 */ public static boolean isEmpty (final Map map..
Read moresrc/resources 폴더 안의 파일 읽기 package io.security.basicsecurity.controller; import java.io .*; public class GetFile { public static void main(String[] args) { FileInputStream file = null; BufferedReader br = null; ClassLoader loader = GetFile.class.getClassLoader(); try { file = new FileInputStream(loader.getResource("F1014/file.txt").getFile()); br = new BufferedReader(new InputStreamReader(file, "..
Read moreString의 계속된 인스턴스 생성 자바 코드에서 만약, 하나의 객체의 기능이 반복이 될 경우 해당 객체와 같은 객체를 여러개 만드는 것보다 하나의 객체를 재사용하는 편이 낫다. 잘못된 String 객체 생성 String s = new String("abd"); 위 코드는 잘못된 코드이다. 문법 상으로는 문제가 없지만, 완전히 쓸데없는 행위이다. 생성자에 넘겨진 “abd” 자체와 생성자의 호출로 만들어지는 String 객체가 기능적으로 완전히 똑같기 때문이다. 위 코드 한줄이 반복문같은 여러번 호출되는 코드라면 String 인스턴스를 무의미하게 수백만개 만들 수 있다. 하나의 String 인스턴스 String s = "abd"; 위 코드 한줄로 String 인스턴스 s를 생성하였고, 만약 “abd”가 필..
Read more필드 어떠한(객체) 데이터를 제공하기 위한 역할을 한다. -필드: 클래스 안에서 선언되는 변수 -지역변수: 메소드, 블록{} 안에서 선언되는 변수 public class Test { // 필드선언 위치 String str; public static void main(String[] args) { Test a = new Test(); a.b(); } public Test() { // 생성자 } public void b() { // 메소드 String v; System.out.println(v); // ERROR -> 지역변수 v는 자동으로 초기화되지 않기때문이다. String str = "JAVA"; System.out.println(str); // 지역변수 str (전역변수 str이 아닌 지역변수 str..
Read moreJAVA 인스턴스 생성 클래스명 객체변수명 = new 클래스명(); Test a = new Test(); 필수적으로 많이 사용하는 코드이지만 이 한줄을 선언함으로써 어떠한 일들이 일어나는지 생각해본적이 없었다. 가장중요한건 이러한 기본지식도 알아야 JAVA 공부를 하는데에 훨씬 많은 도움이 될 것이다. 우선 위 코드는, 인스턴스(객체) 생성시 사용하는 코드이다. 선언된 객체변수 a는 참조값을 갖게된다. new 연산자란? 클래스 타입의 인스턴스(객체)를 생성해주는 역할을 한다. new 연산자를 통해 메모리(Heap) 영역에 데이터를 저장할 공간을 할당받는다. 그 공간의 주소값을 객체변수 a에게 반환해주고 생성자를 호출하게 된다. 생성자란? 인스턴스 변수(필드)들을 초기화해주고 위 예제처럼 선언되어있지 않으..
Read moreI/O 스트림 - 바이트 단위로 데이터를 전송한다. - 실제의 입력과 출력이 표현된 데이터의 흐름이다. - 운영체제에 의해 생성되는 가상의 연결고리 역할을 수행한다. - 출력과 입력의 중간매개체 역할을 한다. - 스트림을 한 방향으로만 통신이 가능하여 입력과 출력을 동시에 실행할 수 없다. - 사용목적에 따라 입력스트림, 출력스트림을 구분한다. (1) 입출력 스트림 입력: InputStream read() return : int -> 더이상 읽어들일 바이트가 없으면 -1을 반환한다. 출력: OutputSTream write() return: void (2) 바이트 기반 스트림 파일 입력: FileInputStream 출력: FileOutputStream 메모리 입력: ByteArrayInputStream..
Read moreArraylist -> 배열 변환 ArrayList files을 MultipartFile[] multiFIles로 변환해보자. MultipartFile[] multiFiles = new MultipartFile[files.size()]; int size = 0; for (MultipartFile file : files) { multiFiles[size++] = file; }
Read more콤마(,)로 구분된 String을 배열로 변환하기 long[] array; try { array = Arrays.stream(custCorpIdxList.split(",")).mapToLong(Long::parseLong).toArray(); } catch (Exception e) { // error 처리 } String a = "1,2,3,4,5" 결과 : long[] array = [1,2,3,4,5] 여기서, 배열의 타입은 원하는 타입으로 선언하면 된다.
Read more에러 발생 Poi 라이브러리를 사용하여 엑셀 다운로드 개발을 하는 도중, 다운로드된 파일을 열때마다 에러가 발생하였다. [파일명]에 읽을 수 없는 내용이 있습니다. 이 통합 문서의 내용을 복구하시겠습니까? 이 통합 문서의 원본을 신뢰할 수 있는 경우 [예]를 클릭하십시오. 이 상태로 [예]를 누르게 되면 파일이 열리면서 아래 메세지가 적힌 팝업이 뜹니다 [파일명.xlsx](으)로 복구 읽을 수 없는 내용을 복구하거나 제거하여 파일을 열 수 있습니다. [복구] 버튼을 누르면 엑셀파일은 알맞게 생성되었지만 열때마다 뜨는 경고창을 해결해야했다. 해결 Before response.setHeader("Set-Cookie", "fileDownload=true; path=/"); response.setHeader("..
Read moreStringUtils if (StringUtils.isEmpty(test)) { test변수가 빈문자열인지, NULL인지 StringUtils 클래스의 isEmpty 메소드를 통해 검사한다. 해당 isEmpty를 보기위해 StringUtils 클래스 파일을 읽어보았다. /** * Check whether the given object (possibly a {@code String}) is empty. * This is effectively a shortcut for {@code !hasLength(String)}. * This method accepts any Object as an argument, comparing it to * {@code null} and the empty String. As a ..
Read more해당 날짜의 몇 달 후 날짜 구하기 DateTimeFormatter DATE_FORMAT = new DateTimeFormatterBuilder() .appendPattern("uuuu-MM-dd HH:mm:ss") .toFormatter(); LocalDateTime startDateTime = LocalDateTime.parse(startDate, DATE_FORMAT); DateTimeFormatter, LocalDateTime 클래스를 사용한다. startDateTime.getMonth().plus(1) plus 메소드를 사용하여 해당 숫자만큼 더해진 월을 구할 수 있다. (ex, 1월 -> plus(3) -> 4월)
Read more두 날짜 사이의 차이 구하기 (startDate, endDate) DateTimeFormatter DATE_FORMAT = new DateTimeFormatterBuilder() .appendPattern("uuuu-MM-dd HH:mm:ss") .toFormatter(); LocalDateTime startDateTime = LocalDateTime.parse(startDate, DATE_FORMAT); LocalDateTime endDateTime = LocalDateTime.parse(endDate, DATE_FORMAT); log.debug("차이 달: " + startDateTime.until(endDateTime,ChronoUnit.MONTHS)); if (startDateTime.until(..
Read moremybatis 쿼리문 실행결과 컬럼(열) 순서를 고정 SELECT col1, col2, col3 FROM test 위 SELECT 해온 쿼리의 결과를 리스트로 받아올때, 리스트의 순서를 col1, col2, col3로 고정시키고 싶은 경우가 있다. 하지만 hashMap을 resultType으로 받는 위 결과를 보면 SELECT 컬럼 순서대로 조회되지 않는다. SELECT col1, col2, col3 FROM test 결과타입 resultType을 "java.util.LinkedHashMap" 으로 변경하면, SELECT 선언 컬럼 순서대로 데이터를 담을 수 있다.
Read moreString, StringBuffer, StringBuild 비교 String, StringBuffer, StringBuild 는 모두 문자열 관련 클래스이다. String은 불변함 (immutable) StringBuffer, StringBuilder는 변함 (mutable) String 객체의 불변함이 무슨뜻인지 알아보자. String test = "a"; CASE1. test += "b"; CASE2. test.concat("b"); 위 간단한 코드에서, test String 객체는 Hip 메모리 영역에 생성된다. 따라서 두번째 코드에서 += 또는 concat 메소드를 사용하였을때 생성되었던 처음 메모리가 아닌, 새로운 메모리를 생성한다. + 연산자, concat 메소드를 통해 새로 생성된 Stri..
Read more