참고: http://www.coderanch.com/t/206099/sockets/java/DatagramPacket-getLength-refresh
아래와 같이 DatagramPacket 을 한번 생성하고
DatagramPacket pack = new DatagramPacket(data, data.length);
매번 pack.setLength(data.length); 로 길이를 초기화해주면 다음에도 pack 을 사용할 수 있다.
2014년 2월 27일 목요일
2013년 4월 13일 토요일
Enumeration (interface)
참고 : http://docs.oracle.com/javase/6/docs/api/java/util/Enumeration.html
Enumeration (interface)
- 사전적 의미로 열거를 말함
Enumeration 인터페이스를 구현한 클래스들은 모두 아래 두 함수 구현체를 갖게 됨.
- boolean hasMoreElements()
- E nextElement()
hasMoreElements() 함수로 다음 읽을 항목이 더 있는지 알 수 있다.
nextElement() 함수로 다음 항목을 얻을 수 있다.
사용예:
Enumeration (interface)
- 사전적 의미로 열거를 말함
Enumeration 인터페이스를 구현한 클래스들은 모두 아래 두 함수 구현체를 갖게 됨.
- boolean hasMoreElements()
- E nextElement()
hasMoreElements() 함수로 다음 읽을 항목이 더 있는지 알 수 있다.
nextElement() 함수로 다음 항목을 얻을 수 있다.
사용예:
package com.enumeration;
import java.util.Enumeration;
import java.util.Hashtable;
public class EnumerationTest {
public static void main(String[] args) throws Exception {
Hashtable table = new Hashtable();
table.put("name", "John");
table.put("age", "24");
table.put("weight", "60kg");
Enumeration keys = table.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
System.out.printf("%s : %s\n", key, table.get(key));
}
}
}
2012년 11월 12일 월요일
String split() 사용
1. 일반적으로 생각하는 split() 함수 사용
> 아래와 같이 String 을 split() 함수를 이용해 나눌 수 있다.
String line = "a,b,c,d,e,f";
String[] result = line.split(",");
결과:
result ==> [a, b, c, d, e, f]
2. delimiter 사이에 빈 문자 처리
> 아래와 같은 경우 빈 string 도 결과 배열에 포함한다.
String line = "a,,c,d,e,f";
String[] result = line.split(",");
결과:
result ==> [a, , c, d, e, f]
> 아래와 같은 경우 빈 string 을 결과 배열에 포함하지 않는다.
String line = "a,,c,d,e,f";
String[] result = line.split("(,+)");
결과:
result ==> [a, c, d, e, f]
설명:
정규 표현 (,+) 의 의미는 , 이 하나 이상을 표현한다.
결국 연달아 , 이 반복되는 경우 하나의 delimiter 로 인식한다.
Regex 참고: http://moonlighting.tistory.com/52
> 아래와 같이 String 을 split() 함수를 이용해 나눌 수 있다.
String line = "a,b,c,d,e,f";
String[] result = line.split(",");
결과:
result ==> [a, b, c, d, e, f]
2. delimiter 사이에 빈 문자 처리
> 아래와 같은 경우 빈 string 도 결과 배열에 포함한다.
String line = "a,,c,d,e,f";
String[] result = line.split(",");
결과:
result ==> [a, , c, d, e, f]
> 아래와 같은 경우 빈 string 을 결과 배열에 포함하지 않는다.
String line = "a,,c,d,e,f";
String[] result = line.split("(,+)");
결과:
result ==> [a, c, d, e, f]
설명:
정규 표현 (,+) 의 의미는 , 이 하나 이상을 표현한다.
결국 연달아 , 이 반복되는 경우 하나의 delimiter 로 인식한다.
Regex 참고: http://moonlighting.tistory.com/52
2012년 10월 4일 목요일
Array 정렬
Arrays.sort() 함수를 이용해 배열을 정렬할 수 있다.
Comparator 를 구현하여 정렬 방식을 조절할 수 있다.
예) 파일 목록을 디렉토리, 파일 순으로 정렬하면서 알파벳 순으로 정렬하는 코드
File[] files = file.listFiles();
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
boolean d1 = f1.isDirectory();
boolean d2 = f2.isDirectory();
if (d1 && !d2) {
return -1;
} else if (!d1 && d2) {
return 1;
} else {
return f1.getName().toUpperCase().compareTo(f2.getName().toUpperCase());
}
}
});
정리) compare() 함수에 -1 을 리턴하면 앞의 값을 앞으로 1 을 리턴하면 뒤의 값을 앞으로 0 을 리턴하면 변경 없이 정렬이 된다.
Comparator 를 구현하여 정렬 방식을 조절할 수 있다.
예) 파일 목록을 디렉토리, 파일 순으로 정렬하면서 알파벳 순으로 정렬하는 코드
File[] files = file.listFiles();
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
boolean d1 = f1.isDirectory();
boolean d2 = f2.isDirectory();
if (d1 && !d2) {
return -1;
} else if (!d1 && d2) {
return 1;
} else {
return f1.getName().toUpperCase().compareTo(f2.getName().toUpperCase());
}
}
});
정리) compare() 함수에 -1 을 리턴하면 앞의 값을 앞으로 1 을 리턴하면 뒤의 값을 앞으로 0 을 리턴하면 변경 없이 정렬이 된다.
2012년 9월 13일 목요일
Pool 예제
솔직히 Pool 에 대해 제가 정확히 이해했는지 자신 없습니다. 아래 내용은 제 사견입니다.
Pool 은 미리 사용하려는 양 만큼의 버퍼를 할당해 놓고 객체를 사용하고 사용한 객체는 다시 버퍼에 넣고 재활용하는 방식의 방법입니다.
이런 방식의 장점으로는 버퍼를 재활용함으로 인해 객체 할당 및 제거에 드는 시간을 없앨 수 있다는 점이 있겠습니다.
Pool.java
- queue 가 두개 필요합니다. 유휴 버퍼와 사용 가능 버퍼로 나눕니다.
- 유휴 버퍼는 미리 빈 객체들로 원하는 갯수 만큼 채워 넣습니다.
- 사용 가능 버퍼에는 유휴 버퍼에서 얻은 사용 객체로 하나씩 채워지게 됩니다.
- 사용 가능 버퍼를 다 사용하고 나면 다시 유휴 버퍼로 옮겨 넣음으로써 나중에 다시 사용 가능하게 됩니다.
소스 코드 :
package pool.test;
import java.util.concurrent.LinkedBlockingQueue;
/**
*
* @param <T>
*/
public class Pool<T> {
private LinkedBlockingQueue<T> free = new LinkedBlockingQueue<T>();
private LinkedBlockingQueue<T> work = new LinkedBlockingQueue<T>();
/**
*
* @param creator
* @param count
*/
public Pool(PoolObjectCreator<T> creator, int count) {
for (int i = 0;i < count; i++) {
free.add(creator.create());
}
}
/**
*
* @return
*/
public final T acquire() {
return free.size() > 0 ? free.remove() : null;
}
/**
*
* @param item
*/
public final void enqueue(T item) {
work.add(item);
}
/**
*
* @return
*/
public final T dequeue() {
return work.size() > 0 ? work.remove() : null;
}
/**
*
* @param item
*/
public final void release(T item) {
free.add(item);
}
/**
*
* @param <T>
*/
public static interface PoolObjectCreator<T> {
public T create();
}
}
아래 내용은 Pool 사용 예제 입니다.- Producer 스레드에서는 1초 마다 pool 에 데이터를 넣습니다.
- Consumer 스레드에서는 pool 에서 데이터를 받아서 화면에 값을 출력합니다.
Main.java :
package pool.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
*
*/
public class Main {
private Consumer consumer;
private Producer producer;
/**
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Main main = new Main();
main.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
reader.readLine();
main.stop();
System.out.println("Done");
}
/**
*
*/
public void start() {
Pool<Container> pool = new Pool<Container>(new Pool.PoolObjectCreator<Container>() {
@Override
public Container create() {
return new Container();
}
} , 10);
producer = new Producer(pool);
consumer = new Consumer(pool);
producer.start();
consumer.start();
}
/**
*
*/
public void stop() {
producer.interrupt();
consumer.interrupt();
}
/**
*
*/
public class Container {
public int x;
}
/**
*
*/
public class Producer extends Thread {
private Pool<Container> pool;
public Producer(Pool<Container> pool) {
this.pool = pool;
}
@Override
public void run() {
super.run();
try {
System.out.println("Producer :: start");
int count = 0;
Container container = null;
while (!Thread.interrupted()) {
if ((container = pool.acquire()) != null) {
container.x = count++;
pool.enqueue(container);
Thread.sleep(1000);
} else {
Thread.sleep(10);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Producer :: done");
}
}
}
/**
*
*/
public class Consumer extends Thread {
private Pool<Container> pool;
public Consumer(Pool<Container> pool) {
this.pool = pool;
}
@Override
public void run() {
super.run();
try {
System.out.println("Consumer :: start");
Container container = null;
while (!Thread.interrupted()) {
if ((container = pool.dequeue()) != null) {
System.out.printf("x : %d\n", container.x);
pool.release(container);
} else {
Thread.sleep(10);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Consumer :: done");
}
}
}
}
2012년 6월 20일 수요일
enum 사용
간단한 선언
예)
String 값을 대입
선언 예)
사용 예)
결과:
Type 1
예)
public enum Types {
TYPE1, TYPE2, TYPE3;
}
String 값을 대입
선언 예)
public enum Types {
TYPE1("Type 1"),
TYPE2("Type 2"),
TYPE3("Type 3");
private String name;
Types(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
사용 예)
package com.enumtest;
public class EnumTest {
public static void main(String[] args) throws Exception {
Types type = Types.TYPE1;
System.out.println(type);
}
}
결과:
Type 1
2012년 3월 19일 월요일
stdin 입력
import java.io.*;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
System.out.println(line);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
System.out.println(line);
2012년 1월 14일 토요일
XML 파싱하기
참고 - http://www.w3.org/TR/REC-xml/
(Extensible Markup Language (XML) 1.0 (Fifth Edition))
XML 파서의 종류는 SAX 파서와 DOM 파서가 있다.
SAX 파서와 DOM 파서의 차이점:
참고 - http://www.ibiblio.org/xml/books/xmljava/chapters/ch09s11.html
(Choosing between SAX and DOM)
> 요약: 어떤 파서를 사용할지는 아래와 같은 상황을 고려하여 선택하는 편이 좋다.
SAX 파서를 사용하는 상황
DOM 파서를 사용하는 상황
(Extensible Markup Language (XML) 1.0 (Fifth Edition))
XML 파서의 종류는 SAX 파서와 DOM 파서가 있다.
SAX 파서와 DOM 파서의 차이점:
참고 - http://www.ibiblio.org/xml/books/xmljava/chapters/ch09s11.html
(Choosing between SAX and DOM)
> 요약: 어떤 파서를 사용할지는 아래와 같은 상황을 고려하여 선택하는 편이 좋다.
SAX 파서를 사용하는 상황
- 파싱하려는 XML 크기가 너무 클 때
- 파싱하려는 XML 중 필요한 정보만 취합하고자 할 때
- 실시간으로 파싱을 처리하고자 할때
DOM 파서를 사용하는 상황
- XML 문서안에 넓게 분포된 자료들 한번에 취합하고자 할 때
- 파싱하려는 XML 문서 구조가 매우 복잡할 때
- XML 문서를 수정할 때
- 파싱한 XML 정보를 여러 함수들이 사용하고자 할 때
파서 사용법:
예) RSS 파일을 파싱하는 예
NY times 사이트의 RSS 링크 중 하나를 선택하여 nyfeed.xml 이라는 파일명으로 저장하였다.
RSS 항목들 중 item 항목에 대한 title 과 link 만 추려서 출력한다.
프로젝트 구조는 아래와 같다.
실행 결과는 아래와 같다.
nyfeed.xml
XMLParseTest.java
같은 일을 하는 함수 두개를 만들었다. domParseTest() 와 saxParseTest() 함수이다.
1. nyfeed.xml 파일을 읽어 파싱한다.
2. item 항목의 title 과 link 내용을 출력한다.
팁)
SAX 파싱 작업 중 더 이상 작업 할 필요가 없을 때는 SAXException 을 날려서 중단하면 된다.
참고 - http://www.ibm.com/developerworks/xml/library/x-tipsaxstop/
예) RSS 파일을 파싱하는 예
NY times 사이트의 RSS 링크 중 하나를 선택하여 nyfeed.xml 이라는 파일명으로 저장하였다.
RSS 항목들 중 item 항목에 대한 title 과 link 만 추려서 출력한다.
프로젝트 구조는 아래와 같다.
실행 결과는 아래와 같다.
DOM 파서
SAX 파서
nyfeed.xml
아래 링크로 접속하여 소스 보기 한 후 내용을 복사하여 프로젝트 폴더에 nyfeed.xml 파일로 저장
http://feeds.nytimes.com/nyt/rss/World
XMLParseTest.java
같은 일을 하는 함수 두개를 만들었다. domParseTest() 와 saxParseTest() 함수이다.
1. nyfeed.xml 파일을 읽어 파싱한다.
2. item 항목의 title 과 link 내용을 출력한다.
package xml.parse;
import java.io.File;
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* XMLParserTest
*/
public class XMLParserTest {
private final String XML_FILE_PATH = "nyfeed.xml";
/**
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
XMLParserTest xpt = new XMLParserTest();
xpt.domParseTest();
xpt.saxParseTest();
}
/**
*
* @throws Exception
*/
public void domParseTest() throws Exception {
System.out.println("==============================");
System.out.println("domParseTest()");
System.out.println("==============================");
File xmlFile = new File(XML_FILE_PATH);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.printf("Root element:%s\n", doc.getDocumentElement().getNodeName());
NodeList itemNodeList = doc.getElementsByTagName("item");
for (int s = 0; s < itemNodeList.getLength(); s++) {
Node itemNode = itemNodeList.item(s);
if (itemNode.getNodeType() == Node.ELEMENT_NODE) {
Element itemElement = (Element)itemNode;
NodeList titleNodeList = itemElement.getElementsByTagName("title");
Element titleElement = (Element)titleNodeList.item(0);
NodeList childTitleNodeList = titleElement.getChildNodes();
System.out.printf("[title : %s]\n", ((Node)childTitleNodeList.item(0)).getNodeValue());
NodeList linkNodeList = itemElement.getElementsByTagName("link");
Element linkElement = (Element) linkNodeList.item(0);
NodeList childLinkNodeList = linkElement.getChildNodes();
System.out.printf("[link : %s]\n", ((Node)childLinkNodeList.item(0)).getNodeValue());
}
}
}
/**
*
* @throws Exception
*/
public void saxParseTest() throws Exception {
System.out.println("==============================");
System.out.println("saxParseTest()");
System.out.println("==============================");
File xmlFile = new File(XML_FILE_PATH);
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
DefaultHandler dh = new DefaultHandler() {
private boolean firstElement = true;
private boolean inItem = false;
private boolean inTitle = false;
private boolean inLink = false;
private StringBuilder characterSB;
@Override
public void startDocument() throws SAXException {
System.out.println("startDocument");
super.startDocument();
}
@Override
public void endDocument() throws SAXException {
System.out.println("endDocument");
super.endDocument();
}
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
if (firstElement) {
System.out.printf("Root element:%s\n", qName);
firstElement = false;
}
if (qName.equals("item")) {
inItem = true;
} else if (qName.equals("title")) {
inTitle = true;
} else if (qName.equals("link")) {
inLink = true;
}
if (inItem && (inTitle || inLink)) {
characterSB = new StringBuilder();
}
super.startElement(uri, localName, qName, attributes);
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (characterSB != null) {
characterSB.append(handleCharacters(ch, start, length));
}
super.characters(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (characterSB != null) {
if (inItem && inTitle) {
System.out.printf("[title : %s]\n", characterSB.toString());
} else if (inItem && inLink) {
System.out.printf("[link : %s]\n", characterSB.toString());
}
characterSB = null;
}
if (qName.equals("item")) {
inItem = false;
} else if (qName.equals("title")) {
inTitle = false;
} else if (qName.equals("link")) {
inLink = false;
}
super.endElement(uri, localName, qName);
}
/**
*
* @param ch
* @param start
* @param end
* @return
*/
public String handleCharacters(char[] ch, int start, int length) {
StringBuilder sb = new StringBuilder();
for (int i = start; i < start + length; i++) {
sb.append(ch[i]);
}
return sb.toString();
}
};
parser.parse(xmlFile, dh);
}
}
팁)
SAX 파싱 작업 중 더 이상 작업 할 필요가 없을 때는 SAXException 을 날려서 중단하면 된다.
참고 - http://www.ibm.com/developerworks/xml/library/x-tipsaxstop/
(Tip: Stop a SAX parser when you have enough data)
throw new SAXException("Enough!");
2012년 1월 11일 수요일
현재 작업 경로 구하기
1. File 클래스 생성자에 '.' 을 입력하면 현재 작업 경로를 얻을 수 있다.
System.out.println(cwd.getAbsoluteFile());
2. System property 에 현재 작업 경로가 저장되어 있다.
System.getProperty("user.dir");
참고 - http://www.roseindia.net/java/example/java/io/GetParentDir.shtml
주의)
첫번째 방법으로 파일을 만들게 되면 parent 를 얻을 수 없는 문제가 있다.
두번째 방법을 이용해서 파일을 만들면 parent 를 얻을 수 있다.
배열을 문자열 또는 리스트로 변환
배열을 문자열로 변환: java.util.Arrays 클래스의 toString() 함수를 이용
String[] array = new String[]{
"a",
"b",
"c"
};
String text = Arrays.toString(array);
System.out.printf("%s\n", text);
결과: [a, b, c]
배열을 리스트로 변환: java.util.Arrays 클래스의 asList() 함수를 이용
String[] array = new String[]{
"a",
"b",
"c"
};
List<String> list = Arrays.asList(array);
System.out.printf("%s\n", list);
결과: [a, b, c]
!) Arrays 클래스를 이용하게 되는 경우 ', ' 구분자에 [] 로 쌓여 있는 문자열을 얻게 된다.
다른 형식의 문자열 결과를 원하는 경우 아래 링크를 참조한다.
Java - How to convert Array to String: http://www.easywayserver.com/blog/java-how-to-convert-array-to-string/
2011년 8월 8일 월요일
List 일부분만 정렬 하기
참고: http://stackoverflow.com/questions/5164902/sorting-a-part-of-java-arraylist
List.subList(int fromIndex, int toIndex) 함수를 사용한다.
예)
[i, a, b, c, d, e, f, g, h]
List.subList(int fromIndex, int toIndex) 함수를 사용한다.
예)
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) throws Exception {
ArrayList<String> list = new ArrayList<String>();
list.add("i");
list.add("e");
list.add("a");
list.add("b");
list.add("g");
list.add("c");
list.add("d");
list.add("f");
list.add("h");
Collections.sort(list.subList(1, list.size()-1));
System.out.println(list.toString());
}
}
결과:[i, a, b, c, d, e, f, g, h]
2011년 8월 3일 수요일
file lastModifed 값을 Date 로 변경
File file = new File("myfile");
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date(file.lastModified()));
cal.getTime(); // Date 값을 return 한다.
2011년 6월 13일 월요일
html 내용 출력
BufferedReader 를 이용하여 html 내용 출력
package http.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class Reader {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.w3.org/");
InputStream is = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
is.close();
}
}
2010년 10월 22일 금요일
File read & write
File 읽기 쓰기하는 경우가 많은데 어떤 클래스를 사용하는지 기억이 잘 안난다.
참고:
사용하는 주요 클래스
BufferedReader 의 생성자에 FileReader 또는 InputStreamReader 등을 넣어준다.
파일경로: 파일 이름을 파일명으로만 주면 프로젝트 폴더에서 파일을 찾는다.
참고:
- file read: http://mwultong.blogspot.com/2006/10/java.html
- file write: http://mwultong.blogspot.com/2006/10/java-text-file-write.html
사용하는 주요 클래스
- BufferedReader -> readline 함수를 사용하여 한줄씩 읽는다.
- BufferedWriter -> write 함수로 쓰고 newline 함수로 개행한다.
BufferedReader 의 생성자에 FileReader 또는 InputStreamReader 등을 넣어준다.
- 파일 읽기 쓰기(FileReader, FileWriter) 또는 http 내용 읽기(InputStreamReader) 에 사용한다.
파일경로: 파일 이름을 파일명으로만 주면 프로젝트 폴더에서 파일을 찾는다.
- 만약 C:\project\file 이 프로젝트 최상위 폴더이고 파일명이 text.txt 이면 C:\project\file\text.txt 을 찾게 된다.
피드 구독하기:
글 (Atom)


