"Java"의 두 판 사이의 차이
둘러보기로 가기
검색하러 가기
잔글 |
잔글 |
||
798번째 줄: | 798번째 줄: | ||
for (Integer number : numbers) { //--- 예전 방식 | for (Integer number : numbers) { //--- 예전 방식 | ||
− | + | System.out.println(number); | |
} | } | ||
806번째 줄: | 806번째 줄: | ||
strings = numbers.stream() | strings = numbers.stream() | ||
− | + | .filter(v -> v > 4) | |
− | + | .map(v -> new String("" + (v + 10))) | |
− | + | .collect(Collectors.toList()); | |
strings.forEach(System.out::println); | strings.forEach(System.out::println); | ||
+ | |||
+ | |||
+ | |||
+ | 스트림의 종류 | ||
+ | |||
+ | *Stream<T> | ||
+ | *IntStream, LongStream, DoubleStream | ||
+ | |||
+ | |||
+ | |||
+ | 병렬 처리 | ||
+ | |||
+ | *순차 처리 스트림 | ||
+ | **numbers.stream() | ||
+ | **numbers.parallelStream().sequential() | ||
+ | *병렬 처리 스트림 | ||
+ | **numbers.parallelStream() | ||
+ | **numbers.stream().parallel() | ||
==문제 해결== | ==문제 해결== |
2014년 11월 13일 (목) 14:18 판
Java, Servlet, JSP에 대한 기본적인 사항을 정리한다.
목차
프로그램 문법
Java 기초
- 주석
// 한줄 짜리 주석 /* 여러줄 짜리 주석 */
상수/변수 선언
- 변수의 선언/삭제 및 적용 범위
연산자
조건문/반복문
오류 처리
- 오류 수집
try { } catch(ex) { } finally { }
코드 변환
- UTF-8로 인코딩 parameter을 서버(Java)에서 받는 방법
request.setCharacterEncoding("utf-8"); String name = request.getParameter("name");
기타 사항
입출력
브라우저 입출력
- URL
URL url = null; HttpURLConnection conn = null; //BufferedWriter out = null; PrintWriter out = null; BufferedReader inp = null; String buf = null; try { url = new URL(requestURL); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.setDoInput(true); //out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "8859_1"), true); out.write("Post data"); out.flush(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { inp = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); while ((buf = inp.readLine()) != null) { System.out.println(buf); } } else { System.out.println("Bad post ... : " + conn.getResponseCode() + " : " + conn.getResponseMessage()); } inp.close(); out.close(); } catch (MalformedURLException e) { System.out.println(e); return false; } catch (IOException e) { System.out.println(e); return false; } finally { if (inp != null) { try { inp.close(); } catch (IOException e) { } inp = null; } if (out != null) { try { out.close(); } catch (Exception e) { } out = null; } }
Cookie 입출력
- Cookie 조회
private String getCookie(HttpServletRequest req, String name) { String rtStr = null; Cookie cookies[] = null; cookies = req.getCookies(); for (int idx = 0;idx < cookies.length;idx++) { if (cookies[idx].getName().equals(name)) { rtStr = cookies[idx].getValue(); break; } } return rtStr; }
- Cookie 등록
Cookie cookie = new Cookie("username", name); cookie.setMaxAge(30*60); //30분... response.addCookie(cookie);
Session 입출력
Container 입출력
콘솔 입출력
파일 입출력
String inputLine = null; File tmpFile = null; BufferedReader inp = null; tmpFile = new File("/docs/hello.html"); try { inp = new BufferedReader(new FileReader(tmpFile)); while ((inputLine = inp.readLine()) != null) { } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inp != null) { try { inp.close(); } catch (IOException e) { e.printStackTrace(); } } inp = null; }
Excel File 입출력
- Library
- Java Excel API : http://www.andykhan.com/jexcelapi/
- POI : http://jakarta.apache.org/poi/index.html
- UtilExcel.java with POI
package com.jopenbusiness.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; //--- HSSF : ~.xls, XSSF : ~.xlsx public class UtilExcel { public static XSSFWorkbook getWorkbook(String fileName) { try { return new XSSFWorkbook(new FileInputStream(new File (fileName))); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static XSSFSheet getSheet(String fileName, String sheetName) { XSSFWorkbook excel = null; excel = getWorkbook(fileName); return (excel == null) ? null:excel.getSheet(sheetName); } public static XSSFCell getCell(XSSFSheet sheet, Integer idxRow, Integer idxCol) { XSSFRow row = null; row = sheet.getRow(idxRow); return (row == null) ? null:row.getCell(idxCol); } public static String getCellType(XSSFCell cell) { if (cell == null) { return "String"; } switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC : return (DateUtil.isCellDateFormatted(cell)) ? "Date/" + cell.getCellType():"Numeric/" + cell.getCellType(); case Cell.CELL_TYPE_STRING : return "String/" + cell.getCellType(); case Cell.CELL_TYPE_FORMULA : return "Formula/" + cell.getCellType(); case Cell.CELL_TYPE_BOOLEAN : return "Boolean/" + cell.getCellType(); case Cell.CELL_TYPE_BLANK : return "Blank/" + cell.getCellType(); case Cell.CELL_TYPE_ERROR : return "Error/" + cell.getCellType(); default : return "Other/" + cell.getCellType(); } } public static String getCellType(XSSFSheet sheet, Integer idxRow, Integer idxCol) { return getCellType(getCell(sheet, idxRow, idxCol)); } public static String getCellString(XSSFCell cell, String defaultValue) { String rtStr = null; if (cell == null) { return defaultValue; } switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING : rtStr = cell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC : if (DateUtil.isCellDateFormatted(cell)) { rtStr = UtilDate.getFormattedDate(cell.getDateCellValue(), UtilDate.SIMPLE_DATE_FORMAT); } else { rtStr = String.valueOf(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN : rtStr = (cell.getBooleanCellValue()) ? "true":"false"; break; case Cell.CELL_TYPE_FORMULA : // rtStr = cell.getCellFormula(); rtStr = cell.getRawValue(); break; case Cell.CELL_TYPE_BLANK : rtStr = cell.getStringCellValue(); break; case Cell.CELL_TYPE_ERROR : rtStr = cell.getErrorCellString(); break; default : rtStr = "/" + cell.getCellType() + "/" + cell.toString() + "/"; } return rtStr; } public static String getCellString(XSSFCell cell) { return getCellString(cell, ""); } public static String getCellString(XSSFSheet sheet, Integer idxRow, Integer idxCol, String defaultValue) { return getCellString(getCell(sheet, idxRow, idxCol), defaultValue); } public static String getCellString(XSSFSheet sheet, Integer idxRow, Integer idxCol) { return getCellString(sheet, idxRow, idxCol, ""); } public static List<String> getRowStrings(XSSFSheet sheet, Integer idxRow, Integer idxColFr, Integer idxColTo) { List<String> rtList = null; rtList = new ArrayList<String>(); for (Integer idx = idxColFr;idx <= idxColTo;idx++) { rtList.add(getCellString(sheet, idxRow, idx)); } return rtList; } public static List<List<String>> getTableStrings(XSSFSheet sheet, Integer idxColFr, Integer idxColTo) { List<List<String>> rtList = null; List<String> rowList = null; Integer cntSkip = null; Integer idxRow = null; String tmpApply = null; idxRow = 0; cntSkip = 0; rtList = new ArrayList<List<String>>(); while (true) { rowList = getRowStrings(sheet, idxRow, idxColFr, idxColTo); if (sheet.getLastRowNum() < idxRow) { break; } idxRow++; tmpApply = rowList.get(0); if ((tmpApply != null) && (tmpApply.equalsIgnoreCase("End Table"))) { break; } if ((tmpApply == null) || (!tmpApply.equals("적용"))) { cntSkip = cntSkip + 1; if (100 < cntSkip) { break; } continue; } cntSkip = 0; rtList.add(rowList); } return rtList; } public static List<String> findRowStrings(XSSFSheet sheet, Integer findIdx, String findStr, Integer idxColFr, Integer idxColTo) { String tmpStr = null; for (Integer idx = sheet.getFirstRowNum();idx <= sheet.getLastRowNum();idx++) { tmpStr = getCellString(sheet, idx, findIdx); if ((tmpStr != null) && (tmpStr.equals(findStr))) { return getRowStrings(sheet, idx, idxColFr, idxColTo); } } return null; } public static String toString(List<String> dataStr) { String rtStr = null; for (String item : dataStr) { rtStr = (rtStr == null) ? "":rtStr + ", "; rtStr = rtStr + "[" + item + "]"; } return rtStr; } }
Java Reflection
Java에서 제공하는 Java Reflection 기능을 사용하면 동적으로 Class, Method를 관리할 수 있다.
- Java Reflection Class (rt.jar)
- sun.reflect
- Reflection, ReflectionFactory
- sun.refletc.misc
- ConstructorUtil, FieldUtil, MethodUtil, ReflectUtil, Trampoline
- 사용 예 1
try { Class c = Class.forName(args[0]); //--- c = String.class Method m[] = c.getDeclaredMethods(); //--- getDeclaredMethods()메소드 대신 getMethods()를 사용하게 되면, 상속된 메소드의 정보까지 얻을수있다. for (int i = 0; i < m.length; i++) System.out.println(m[i].toString()); } catch (Throwable e) { System.err.println(e); }
//--- 생성자 반환 Constructor ctorlist[] = cls.getDeclaredConstructors();
Class cls = Class.forName("A"); boolean b1 = cls.isInstance(new Integer(37));
Field fieldlist[] = cls.getDeclaredFields();
//-- Method 실행 Class cls = Class.forName("method2"); Class partypes[] = new Class[2]; partypes[0] = Integer.TYPE; partypes[1] = Integer.TYPE; Method meth = cls.getMethod( "add", partypes); method2 methobj = new method2(); Object arglist[] = new Object[2]; arglist[0] = new Integer(37); arglist[1] = new Integer(47); Object retobj = meth.invoke(methobj, arglist); Integer retval = (Integer)retobj; System.out.println(retval.intValue());
//--- 클래스 생성 Class cls = Class.forName("constructor2"); Class partypes[] = new Class[2]; partypes[0] = Integer.TYPE; partypes[1] = Integer.TYPE; Constructor ct = cls.getConstructor(partypes); Object arglist[] = new Object[2]; arglist[0] = new Integer(37); arglist[1] = new Integer(47); Object retobj = ct.newInstance(arglist);
//--- 배열 관리 try { Class cls = Class.forName( "java.lang.String"); Object arr = Array.newInstance(cls, 10); Array.set(arr, 5, "this is a test"); String s = (String)Array.get(arr, 5); System.out.println(s);
- 참고 문헌
Shutdown 관리
- Shutdown 상황
- Throwable
- Exception, Error
- SIGINT : Ctrl_C, ShutdownHook 호출됨
- SIGTERM : kill ~, ShutdownHook 호출됨
- SIGKILL : kill -9 ~
자주 사용하는 Class
HashMap
HashMap<String, Object> map = new HashMap<String, Object>(); map.put("name", "value"); for (Map.Entry<String, Object> entry : processInfo.entrySet()) { entry.getKey(), entry.getValue() }
ArrayList
사용자 정의 라이브러리
윈도우 Command Line에서 Java 프로그램 실행
- extractHtml.vbs (WScript 파일)
'=============================================================================== ' 프로그램 명 : /extractHtml.vbs ' 프로그램 설명 : Java를 컴파일하고 실행하기 위한 스크립트 ' 작성자 : 산사랑 ' 작성일 : 2008.07.08 ~ 2008.07.08 '------ [History 관리] --------------------------------------------------------- ' 수정자 : ' 수정일 : ' 수정 내용 : '------ [Copyright] ------------------------------------------------------------ ' Copyright (c) 1995-2008 pnuskgh, All rights reserved. '=============================================================================== On Error Resume Next '------------------------------------------------------------------------------- ' Main Routine '------------------------------------------------------------------------------- Dim objShell Set objShell = CreateObject("WScript.Shell") 'objShell.Run "cmd /C ""javac extractHtml.java & java extractHtml & notepad extractHtml.out & pause""" objShell.Run "cmd /C ""javac extractHtml.java & java extractHtml & notepad extractHtml.out""" Set objShell = Nothing '=============================================================================== ' 프로그램 명 : /ant_run.vbs '===============================================================================
DES 암복호화
- DES 암호화, 복호화 모듈
public class UtilCrypto { public static Key desKey = null; public static Key getDesKey() { if (desKey == null) { desKey = makeDesKey(); } return desKey; } public static void setDesKey(Key desKey) { UtilCrypto.desKey = desKey; } public static Key makeDesKey() { KeyGenerator generator = null; try { generator = KeyGenerator.getInstance("DES"); // generator = KeyGenerator.getInstance("TripleDES"); // generator = KeyGenerator.getInstance("AES"); generator.init(new SecureRandom()); return generator.generateKey(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static String crypt(String algorithm, Integer cryptMode, Key key, String inpStr) { String rtStr = null; Cipher cipher = null; if ((inpStr == null) || (inpStr.length() == 0)) { return ""; } try { if (algorithm.equals("DES")) { cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); } else if (algorithm.equals("TripleDES")) { cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding"); } else if (algorithm.equals("RSA")) { cipher = Cipher.getInstance("RSA"); } else { cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); } if (cryptMode == Cipher.ENCRYPT_MODE) { cipher.init(Cipher.ENCRYPT_MODE, key); rtStr = Base64Encoder.encode(cipher.doFinal(inpStr.getBytes("UTF-8"))); } else { cipher.init(Cipher.DECRYPT_MODE, key); rtStr = new String(cipher.doFinal(Base64Decoder.decodeToBytes(inpStr)), "UTF-8"); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rtStr; } public static String encryptDes(String plain) { return crypt("DES", Cipher.ENCRYPT_MODE, getDesKey(), plain); } public static String decryptDes(String security) { return crypt("DES", Cipher.DECRYPT_MODE, getDesKey(), security); } }
RSA 암복호화
public class UtilCrypto { public static KeyPair rsaKey = null; public static KeyPair getRsaKeyPair() { if (rsaKey == null) { rsaKey = makeRsaKeyPair(); } return rsaKey; } public static Key getRsaPublicKey() { if (rsaKey == null) { getRsaKeyPair(); } return rsaKey.getPublic(); } public static Key getRsaPrivateKey() { if (rsaKey == null) { getRsaKeyPair(); } return rsaKey.getPrivate(); } public static void setRsaKeyPair(KeyPair rsaKey) { UtilCrypto.rsaKey = rsaKey; } public static KeyPair makeRsaKeyPair() { KeyPairGenerator generator = null; try { generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); //--- keysize return generator.genKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static String encryptRsa(String plain) { return crypt("RSA", Cipher.ENCRYPT_MODE, getRsaPublicKey(), plain); } public static String decryptRsa(String security) { return crypt("RSA", Cipher.DECRYPT_MODE, getRsaPrivateKey(), security); } }
사용자 정의 프로그램
HTML에서 원하는 문자열 추출
- extractHtml.java : 여러 페이지로 작성된 HTML에서 원하는 문자열을 추출하는 프로그램, 필요시 수정하여 사용하세요.
//============================================================================== // 프로그램 명 : extractHtml.java, Version 0.01 // 프로그램 설명 : HTML에서 원하는 문자열을 추출 // 작성자 : 산사랑 // 작성일 : 2008.07.08 ~ 2008.07.08 //----- [History 관리] --------------------------------------------------------- // 수정자 : // 수정일 : // 수정 내용 : //----- [Copyright] ------------------------------------------------------------ // Copyright (c) 1995-2008 pnuskgh, All rights reserved. //============================================================================== import java.io.*; import java.net.*; class extractHtml { public static void main(String args[]) { int idx = 0, checkIdx = 0, cntRead = 0; URL url = null; String strUrl = "http://serverHost/main.php?catid=&skey=&page="; String inputLine = null; BufferedReader inp = null; BufferedWriter out = null; File outFile = null; String fileNameOut = "extractHtml.out"; String delimiter = "|"; try { outFile = new File(fileNameOut); if (outFile.exists()) { outFile.delete(); } out = new BufferedWriter(new FileWriter(outFile)); for (idx = 1;idx <= 221;idx++) { url = new URL(strUrl + idx); inp = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = inp.readLine()) != null) { if (-1 < inputLine.indexOf("main.php?in=building_detail")) { checkIdx = checkIdx + 1; if (checkIdx == 1) { out.write(idx + delimiter + ++cntRead + delimiter); out.write(inputLine.substring(inputLine.lastIndexOf("'>") + 2, inputLine.indexOf("</a>")) + delimiter); } if (checkIdx == 2) { out.write(inputLine.substring(inputLine.lastIndexOf("'>") + 2, inputLine.indexOf("</a>")) + delimiter); } } if (-1 < inputLine.indexOf("/main.php?in=corp_detail&type=corp")) { checkIdx = checkIdx + 1; if (checkIdx == 5) { out.write(inputLine.substring(inputLine.lastIndexOf("'>") + 2, inputLine.indexOf("</a>")) + delimiter); out.write("http://serverHost/main.php?id=" + inputLine.substring(inputLine.indexOf("id=") + 3, inputLine.indexOf("page=") - 1) + "\r\n"); checkIdx = 0; } else { out.write(inputLine.substring(inputLine.lastIndexOf("'>") + 2, inputLine.indexOf("</a>")) + delimiter); } } } inp.close(); } out.flush(); out.close(); } catch (Exception e) { System.out.println(e); } finally { if (inp != null) { try { inp.close(); } catch (IOException e) { e.printStackTrace(); } } inp = null; if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } out = null; } } } //============================================================================== // 프로그램 명 : extractHtml.java //==============================================================================
UUID 생성
- Universally Unique Identifier(또는 Globally Unique Identifier)의 종류
- v1 : MAC address based
- v2 : DCE Security based
- v3 : Name based + MD5 hash
- v4 : Random
- v5 : Name based + SHA1 hash
- UUID의 구성
- 128 bits (16 bytes) 숫자
- 8-4-4-4-12 형태의 36개의 문자열
- Sample
package kr.co.daou.common; import java.util.Random; import java.util.UUID; import org.safehaus.uuid.UUIDGenerator; public class GUID { private static Random rand = null; public static void main(String args[]) { System.out.println("Unique ID Generation Test"); for (int cnt = 0;cnt < 100;cnt ++) { System.out.println(getPrefixUUID("user")); } } public static String getPrefixUUID(String prefix) { return prefix + "." + getUUID1(); } public static String getUUID() { return getUUID1(); } //--- MAC address based, uuid-3.2.jar (MIT License) 사용 public static String getUUID1() { return (new com.eaio.uuid.UUID()).toString(); } //--- Name based + MD5 hash, java.util.UUID 사용 public static String getUUID3() { return getUUID3("Hello World!"); } public static String getUUID3(String seed) { seed = seed + Long.toString(rand.nextLong()); return UUID.nameUUIDFromBytes(seed.getBytes()).toString(); } //--- Random, java.util.UUID 사용 public static String getUUID4() { return UUID.randomUUID().toString(); } //--- Random, jug-lgpl-2.0.0.jar (GNU LGPL) 사용 public static String getUUID4_1() { return UUIDGenerator.getInstance().generateRandomBasedUUID().toString(); } //--- jug-lgpl-2.0.0.jar (GNU LGPL) 사용 public static String getUUID_jug() { return UUIDGenerator.getInstance().generateTimeBasedUUID().toString(); } static { rand = new Random(System.currentTimeMillis()); } }
- 참고 문헌
Java 8
- Eclipse LUNA에서 Java 8을 공식적으로 지원
- Jigsaw
- 참고 문헌
- Java 8 개선 사항 관련 글 모음, 2014.05
- [http://www.techempower.com/blog/2013/03/26/everything-about-java-8/ http://www.techempower.com/blog/2013/03/26/everything-about-java-8/]
- [http://www.techempower.com/blog/2013/03/26/everything-about-java-8/ [http://www.oracle.com/kr/corporate/magazines/winter-tech2-1429486-ko.pdf http://www.oracle.com/kr/corporate/magazines/winter-tech2-1429486-ko.pdf]]
람다식 (Lambda Expression)
- 함수형 프로그램밍을 통해 멀티 코어 CPU 지원
- 람다식 형태
- (x, y) -> { x + y }
- (x, y) -> x + y
- x -> x + 5
//--- 함수형 인터페이스 : 추상 메서드가 한개인 인터페이스 @FunctionalInterface public interface funcArg { int methodOne(int a, int b); } funcArg aa = (a, b) -> { return a + b } public void test(int one, int two, funcArg arg1) { arg1.methodOne(one, two); } test(1, 2, aa);
Stream (Java Collection API)
- Collection을 Pipe 형식으로 처리하는 함수형 API 지원
- Collection (List, Map, Set)을 Stream으로 처리
- java.util.stream
List<Integer> numbers = null; List<String> strings = null; numbers = Arrays.asList(1, 2, 3, 4, 5, 6); for (Integer number : numbers) { //--- 예전 방식 System.out.println(number); } numbers.forEach(value -> System.out.println(value)); //--- 최신 방식 //--- numbers.forEach((Integer value) -> System.out.println(value)); //--- numbers.forEach(System.out::println); strings = numbers.stream() .filter(v -> v > 4) .map(v -> new String("" + (v + 10))) .collect(Collectors.toList()); strings.forEach(System.out::println);
스트림의 종류
- Stream<T>
- IntStream, LongStream, DoubleStream
병렬 처리
- 순차 처리 스트림
- numbers.stream()
- numbers.parallelStream().sequential()
- 병렬 처리 스트림
- numbers.parallelStream()
- numbers.stream().parallel()
문제 해결
- "java.lang.OutOfMemoryError: PermGen space" 오류가 발생할 경우 다음 옵션을 준다.
-Xms512m -Xmx1024m -XX:PermSize=64M //--- 해당 옵션 -XX:MaxPermSize=128M //--- 해당 옵션 -verbose:gc -verbose:class