반응형

우선 byte[] 합치기 예제

배열을 합칠 바이트 배열을 만들고

System.arraycopy 를 이용해서 새로 만든 바이트 배열에 header 및 body 의 바이트값을 넣어준뒤 보내주면 되겠네요

아래 소스 참고해서 적용해보세요

public class test {
 public static void main(String[] args) {
  String body = "abcdefg";  
  byte [] header = {
      (byte)0x00, (byte)0x00, (byte)0x4E, (byte)0x20, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x2F, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00
     };
 

 byte[] temp = body.getBytes(); // 문자열을 바이트 배열로 변환

 

 byte[] data = new byte[temp.length + header.length]; // body와 header를 담을 바이트배열생성 

  
  System.arraycopy(header, 0, data, 0, header.length);

 

// data 배열의 0번째 인덱스에 header 배열의 0번째 인덱스부터 header 의 길이만큼 복사


  System.arraycopy(temp, 0, data, header.length, temp.length);

  // data 배열에 header.length 만큼의 인덱스에 temp 배열의 0번째 인덱스부터 body 의 길이만큼 복사

  for (int i=0; i<data.length; i++)="" {<br="">    System.out.println(data[i]);
  }
 }</data.length;>

}

 

 

참고로 arraycopy 의 api 를 보면

arraycopy

(Object  src, int srcPos, Object  dest, int destPos, int length)

src - 카피할 소스

srcPos - 카피할 소스의 시작 위치, 인덱스

dest - 카피받을(?) 객체

destPos - 카피받을 시작 인덱스

int length - 카피할 길이

 

===========================================================

 

Java에서 System.arraycopy() 사용법

 

전체 데이터가 있을 때, 그 특정 부분만 빼오고 싶을 때가 있습니다.

 

데이터를 하나씩 읽어가다가 내가 찾는 번지가 나올 때부터 값을 저장하게 하고, 일정 갯수나 위치 만큼 까지만 읽어오게 한다면... 할 수 있지만, 상당히 귀찮은 일입니다.

 

이런 경우에 쉽게 사용할 수 있는게 System.arraycopy입니다.

배열에서 원하는 부분만 복사한다는 의미로 생각하면 됩니다.

 

 

1. System.arraycopy()

 

Java 코드를 주로 이클립스에서 작성을 하는데,  System.arraycopy() 라고 입력을 합니다.

 

System.arraycopy(arg0, arg1, arg2, arg3, arg4);

 

예전에는 자세히 뜬거 같은데, 요즘엔 arg 라는 값만 떠서 헷갈리게 합니다.

이런 경우에는, arraycopy 부분에 마우스를 클릭하면 F2를 누르면 자세한 설명이 나옵니다.

 

 

 

2. System.arraycopy() 요소

 

Object src : 복사하고자 하는 소스입니다. 원본이라고 생각하면 됩니다.

 

int srcPos : 위의 소스에서 어느 부분부터 읽어올지 위치를 정해줍니다.

 

Object dest : 원본이 있다면 복사본이 있어야겠지요. 복사하려는 대상입니다.

 

int destPos : 위의 dest에서 자료를 받을 때, 어느 부분부터 쓸지 시작 위치를 정해줍니다.

 

int length : 원본에서 복사본까지 얼마큼 읽어 올지 입력하는 것 입니다.

 

간단하게 앞의 2개는 src(원본)에 관한 것이고, 그 뒤에 2개는 dest(복사본), 마지막으로 length는 가져올 길이라고 생각하면 됩니다.

 

 

3. System.arraycopy() 예제 1

 

사용법에 대해서 설명을 들었으니, 간단하게 예제를 들어보도록 하겠습니다.

 

원본 배열 이름은 src 라고 하고 복사본은 dest 라고 하겠습니다.

 

원본 배열은 아래와 같이 00 ~ 0F 까지 차례대로 데이터를 넣었습니다.

복사된 내용을 넣을 배열은 4 바이트 만큼 잡았습니다.

 

byte[] src = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 ... 0x0F }
byte[] dest = new byte[4];

 

이제 System.arraycopy를 사용할 차례입니다.

 

위에서 배운대로 먼저 배열을 넣어줍니다.

 

System.arraycopy(src, ?,

dest

, ?, ?);

 

그 다음엔 원본에 첫 번째 있는 데이터를 복사본 길이 만큼 넣어주려고 합니다.

src 다음에 0이라고 입력하여, 원본의 첫 데이터부터 복사한다고 정해줍니다.

그 다음 복사된 데이터를 dest의 첫 번째 자리부터 넣을거라고 0이라고 입력을 합니다.

 

System.arraycopy(src,

0

, dest,

0

, ?);

 

그 다음 dest 의 길이인 4 만큼 넣을 것이므로 제일 마지막엔 4 라고 입력을 해줍니다.

 

System.arraycopy(src, 0, dest, 0, 4);

 

System.arraycopy를 실행 후에, dest 의 값을 출력하도록 합니다.

아래와 같이 원본의 처음 데이터부터 4번째까지 데이터가 들어왔습니다.

 

dest 값
0x00, 0x01, 0x02, 0x03

 

 

3. System.arraycopy() 예제 2

 

이번에는 원본에서 처음이 아닌 특정 위치 데이터를 복사본의 특정 위치에 복사를 해보도록 하겠습니다.

 

byte[] src = { 0x01, 0x02, 0x03, 0x04, 0x05 ... 0x0F }
byte[] dest = new byte[8];

 

먼저 dest를 출력을 해봅니다.

선언 후에 데이터가 없기 때문에 0으로 출력이 됩니다.

 

dest 값
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00

 

원본에 있는 데이터를 0x03부터 0x06 까지만 복사하고 싶습니다.

0x03 의 위치인 2를 입력합니다.

 

그 다음 0x03~0x06 는 갯수가 4개 이므로 4을 입력합니다.

 

System.arraycopy(src,

2

, dest, ?,

4

);

 

이번에는 dest 기준으로 0 이라고 입력하면 처음부터 복사한 데이터를 저장할 것입니다.
이번엔 4번째부터 넣을 예정이니 3이라고 입력을 합니다.

 

System.arraycopy(src, 2, dest,

3

, 4);

 

System.arraycopy를 수행한 후에 dest 값을 출력해봅니다.

아래와 같이 원하는 위치에 들어가면 문제 없이 출력이 된 것입니다.

 

dest 값
0x00, 0x00, 0x00, 0x03, 0x04, 0x05, 0x06, 0x00

 

반응형
LIST
반응형

자바(Java) Reflect 예제 동적 Method 호출

 
ReflectMethod.java
 
001.package reflect;
002. 
003.public class ReflectMethod {
004.  
005.   //field
006.   public String field;
007.  
008.   //constructor
009.   public ReflectMethod() {}
010. 
011.   public ReflectMethod(String field) {
012.      this.field = field;
013.   }
014.  
015.   //method
016.   public String getField() {
017.      System.out.println("call field : " + this.field);
018.      return this.field;
019.   }
020.   public void methodA() {
021.      System.out.println("call method A");
022.   }
023.   public void methodB(String str) {
024.      System.out.println("call method B : " + str);
025.   }
026.   public String methodC() {
027.      System.out.println("call method C");
028.      return "method C";
029.   }
030.}
031. 
032.ReflectMain.java
033. 
034.package reflect;
035. 
036.import java.lang.reflect.Constructor;
037.import java.lang.reflect.Field;
038.import java.lang.reflect.InvocationTargetException;
039.import java.lang.reflect.Method;
040. 
041.public class ReflectMain {
042.   public static void main(String[] arguments) throws
043.                                         ClassNotFoundException,
044.                                         InstantiationException,
045.                                         IllegalAccessException,
046.                                         SecurityException,
047.                                         NoSuchMethodException,
048.                                         IllegalArgumentException,
049.                                         InvocationTargetException,
050.                                         NoSuchFieldException {
051.   
052.  /*
053.   * 원시형 클래스 타입
054.   * char : Character.TYPE
055.   * byte : Byte.TYPE
056.   * short : Short.TYPE
057.   * int : Integer.TYPE
058.   * long : Long.TYPE
059.   * float : Float.TYPE
060.   * double : Double.TYPE
061.   */
062.   
063.      //클래스 가져오기
064.      Class getClass1 = Class.forName("reflect.ReflectMethod");
065.      Class getClass2 = ReflectMethod.class;
066.      Class getClass3 = new ReflectMethod().getClass();
067.   
068.      //클래스 객체를 이용한 객체 생성
069. 
070.      //생성자에 인자가 없는 경우
071.      Object object1 = getClass1.newInstance();
072.      //생성자에 인자가 있을 경우
073.      Class[] constructorParamClass = new Class[] {String.class};
074.      Object[] constructorParamObject = new Object[] {"Reflect Test!!!"};
075.      Constructor constructor = getClass1.getConstructor(constructorParamClass);
076.      Object object2 = constructor.newInstance(constructorParamObject);
077. 
078.      //필드 값 가져오기
079.      Field field = getClass1.getField("field");
080.      Object fieldObject = field.get(object2);
081.   
082.      System.out.println(fieldObject);
083.   
084.      //메소드 호출
085.   
086.      //메소드에 인자가 없는 경우
087.      Method method1 = getClass1.getMethod("methodA");
088.      method1.invoke(object1);
089.      //메소드에 인자가 있을 경우
090.      Class[] methodParamClass = new Class[] {String.class};
091.      Object[] methodParamObject = new Object[] {"1 parameter"};
092.      Method method2 = getClass1.getMethod("methodB", methodParamClass);
093.      method2.invoke(object1, methodParamObject);
094.      //메소드에 리턴값이 있을 경우
095.      Method method3 = getClass1.getMethod("methodC");
096.      Object returnObject = method3.invoke(object1);
097.   
098.      System.out.println("methodC return value : " + returnObject);
099.   }
100.}

콘솔출력결과
Reflect Test!!!

call method A
call method B : 1 parameter
call method C
methodC return value : method C

 

반응형
LIST
반응형

Java Map 반복(Iteration)시키는 3가지 방법

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
package com.tistory.stove99;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class MapIterationSample {
    public static void main(String[] agrs) {
        Map<String, String> map = new HashMap<String, String>();
         
        map.put("키1", "값1");
        map.put("키2", "값2");
        map.put("키3", "값3");
        map.put("키4", "값4");
        map.put("키5", "값5");
        map.put("키6", "값6");
         
         
        // 방법1
        Iterator<String> keys = map.keySet().iterator();
        while( keys.hasNext() ){
            String key = keys.next();
            System.out.println( String.format("키 : %s, 값 : %s", key, map.get(key)) );
        }
         
        // 방법2
        for( Map.Entry<String, String> elem : map.entrySet() ){
            System.out.println( String.format("키 : %s, 값 : %s", elem.getKey(), elem.getValue()) );
        }
         
        // 방법3
        for( String key : map.keySet() ){
            System.out.println( String.format("키 : %s, 값 : %s", key, map.get(key)) );
        }
    }
}

 

반응형
LIST
반응형

Java SimpleDateFormat

The java.text.SimpleDateFormat class is used to both parse and format dates according to a formatting pattern you specify yourself.

This text explains how to use the SimpleDateFormat class to format dates.

Creating a SimpleDateFormat

You create a SimpleDateFormat instance like this:

String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

The pattern String parameter passed to the SimpleDateFormat constructor is the pattern to use for parsing and formatting of dates. The pattern syntax is covered later in this text.

Formatting Dates

Once you have created a SimpleDateFormat instance you can format dates using its format() method. Here is an example:

String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

String date = simpleDateFormat.format(new Date());
System.out.println(date);

The Date instance passed to the format() method is a java.util.Date instance.

The output printed from this code would be:

2012-11-03

Parsing Dates

You can parse a String into a java.util.Date instance using the parse() method of the SimpleDateFormat instance. Here is an example:

String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

Date date = simpleDateFormat.parse("2012-12-24");

Once this code is executed, the date variable points to a Date instance representing december 24th, 2012.

Creating a SimpleDateFormat For a Specific Locale

You can create a SimpleDateFormat instance targeted at a specific Locale. Doing so will format the dates according to that Locale whenever relevant. For instance, a formatting pattern including the name of the week day will write the week day in the language of the given Locale. Here is an example:

String pattern = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ";
SimpleDateFormat simpleDateFormat =
        new SimpleDateFormat(pattern, new Locale("da", "DK"));

String date = simpleDateFormat.format(new Date());
System.out.println(date);

The output printed from this code could be:

lørdag november 2012 10:38:45.156+0100

Notice how week day (lø = saturday) and month (november) is written in Danish.

Pattern Syntax

You can use the following symbols in your formatting pattern:

G Era designator (before christ, after christ)
y Year (e.g. 12 or 2012). Use either yy or yyyy.
M Month in year. Number of M's determine length of format (e.g. MM, MMM or MMMMM)
d Day in month. Number of d's determine length of format (e.g. d or dd)
h Hour of day, 1-12 (AM / PM) (normally hh)
H Hour of day, 0-23 (normally HH)
m Minute in hour, 0-59 (normally mm)
s Second in minute, 0-59 (normally ss)
S Millisecond in second, 0-999 (normally SSS)
E Day in week (e.g Monday, Tuesday etc.)
D Day in year (1-366)
F Day of week in month (e.g. 1st Thursday of December)
w Week in year (1-53)
W Week in month (0-5)
a AM / PM marker
k Hour in day (1-24, unlike HH's 0-23)
K Hour in day, AM / PM (0-11)
z Time Zone
' Escape for text delimiter
' Single quote

Characters other than these will be treated as normal text to insert into the pattern, and thus into the formatted dates.

Some characters can be used in different numbers. For instance, you can write either yy for a 2-character version of the year (e.g. 12), or you can write yyyy for a 4-character version of the year (e.g. 2012). For more information about the patterns accepted, see the JavaDoc for the SimpleDateFormat class.

Pattern Examples

Here are a few patterns examples:

Pattern Example
dd-MM-yy 31-01-12
dd-MM-yyyy 31-01-2012
MM-dd-yyyy 01-31-2012
yyyy-MM-dd 2012-01-31
yyyy-MM-dd HH:mm:ss 2012-01-31 23:59:59
yyyy-MM-dd HH:mm:ss.SSS 2012-01-31 23:59:59.999
yyyy-MM-dd HH:mm:ss.SSSZ 2012-01-31 23:59:59.999+0100
EEEEE MMMMM yyyy HH:mm:ss.SSSZ Saturday November 2012 10:45:42.720+0100

DateFormatSymbols

It is possible to customize the date symbols used in the formatted output, for a specific Locale. You do so using a java.text.DateFormatSymbols instance. Here is an example:

Locale locale = new Locale("en", "UK");
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(locale);
dateFormatSymbols.setWeekdays(new String[]{
        "Unused",
        "Sad Sunday",
        "Manic Monday",
        "Thriving Tuesday",
        "Wet Wednesday",
        "Total Thursday",
        "Fat Friday",
        "Super Saturday",
});

String pattern = "EEEEE MMMMM yyyy";
SimpleDateFormat simpleDateFormat =
        new SimpleDateFormat(pattern, dateFormatSymbols);

String date = simpleDateFormat.format(new Date());
System.out.println(date);

First a new DateFormatSymbols instance is created for the UK Locale.

Second, a new set of names for week days is set. Notice that the first string "unused" is never used. The indices in this array must start from one, to be indexable by the Calendar.SUNDAY, Calendar.MONDAY etc. constants. The Calendar.SUNDAY constant is 1, Calendar.MONDAY is 2 etc.

Third a SimpleDateFormat is created using the DateFormatSymbols, and a date is formatted with it. The output printed from this could would look like this:

Super Saturday November 2012

Notice how the custom week day name is used.

You can set more date formatting symbols on the DateFormatSymbols instance. Here are the methods you can use to set additional symbols:

dateFormatSymbols.setWeekdays();
dateFormatSymbols.setAmPmStrings();
dateFormatSymbols.setEras();
dateFormatSymbols.setLocalPatternChars();
dateFormatSymbols.setMonths();
dateFormatSymbols.setShortMonths();
dateFormatSymbols.setShortWeekdays();
dateFormatSymbols.setZoneStrings();

See the JavaDoc for the java.text.DateFormatSymbols class for more details about these methods and symbols.

 

반응형
LIST

+ Recent posts