[Node.js] 문자열 기능 ( 붙이기, 자르기, 길이 얻어오기 )



Node.js는 기본적으로 자바스크립트와 유사하다. 자바스크립트를 할 줄 알면 Node.js를 코드를 보는데 어려움이 없을 것이다. Node.js에서 문자열을 다루는 방법에 대해 설명 하지만 이 기능들은 javascript에서도 동일하게 사용 된다.


문자열 입력, 출력, 길이 얻어오기



[문자열 입력, 출력, 길이 얻어오기]

//문자열 입력

var text = "test value";


//문자열 출력

console.log("text : " + text );


//문자열 길이 얻어오기

console.log("text length : " + text.length );


[실행 결과]

text : test value

text length : 10


[문자열 길이 얻어오는 문자열 변수]

console.log("text length : " + text.length )


문자열 자르기, 붙이기



[문자열 입력, 출력, 길이 얻어오기]

//문자열 입력

var text = "test value";


//문자열 자르기

var sub_text = text.substring(0,4);

console.log("sub_text : " + sub_text );


//문자열 붙이기

var new_text = " new text";

var sum_text = text + new_text;

console.log("sum_text : " + sum_text );


text += "plus text";

console.log("text : " + text );


[실행 결과]

sub_text : test

sum_text : test value new text

text : test valueplus text


[문자열 길이 자르기]

text의 값이 "test value"이다. 여기서 substring 함수는 시작 지점인 0부터 끝 지점인 4이전 까지 값을 가져오는 기능을 한다.

0 -> t, 1 ->e, 2->s, 3->t 해서 test라는 값을 얻어와 sub_text에 담는 역할을 한다.

var sub_text = text.substring(0,4);


[문자열 길이 붙이기]

+를 사용해 두 문자열을 합칠 수 있다.

var sum_text = text + new_text;


또한 += 기존의 문자열 뒤에 이어 붙일 수도 있다.

text += "plus text";



반응형

디컴파일러 Class 파일 -> java 파일로 보는 방법



자바에서 사용하는 API의 소스 내용을 확인 하고 싶을 때가 있을 것이다. 하지만 API는 class 파일로 되어 있어 확인이 어려운데 디컴파일러를 이용해 java파일로 변환해 소스를 보는 방법을 확인해 보겠다.


JAVA Decomplier



[Decomplier 다운]

아래 사이트에서 JD-GUI를 다운 받아서 class 파일을 java 소스 파일로 볼 수 있다.

http://jd.benow.ca/


이클립스에서 class -> java 변환 방법



[이클립스에 디컴파일러 플러그인 설치 방법]

아래 사이트에서 JD-Ecplise를 다운 받는다.

http://jd.benow.ca/


다운 받은 파일을 확인 한다.

jd-eclipse-site-1.0.0-RC2.zip


이클립스에서 다운 받은 파일을 설치 한다.

이클립스 실행 -> help -> Install New Software -> add -> Archive.... -> 

다운 받은 jd-eclipse-site-1.0.0-RC2.zip 파일 선택 -> java Decompiler Eclipse Plug-in 선택 - > next


String 클래스를 선택해 본다.

소스 중 String이 정의 된 곳에 Ctrl 키를 누르고 String을 마우스 왼쪽으로 클릭한다.

그럼 String 클래스의 java파일인 소스 내용을 확인 할 수 있다.


반응형

'프로그램 > Java' 카테고리의 다른 글

[java] NIO를 이용한 파일 쓰고 읽기  (0) 2018.06.05
[java] ByteBuffer 사용법  (0) 2018.06.03
[java] 파일 읽고,쓰기 사용법  (0) 2018.05.30
[java] 스레드 사용법  (0) 2018.05.27
[java] 함수 가변 인자 사용 방법  (0) 2018.05.25

NIO를 이용한 파일 쓰고 읽기(GatheringByteChannel, ScatteringByteChannel)



보통 자바가 C에 비에 느린 이유중 하나가 IO가 JVM 내부에 IO버퍼를 두었기 때문이다. java에서 IO 프로그램을 할 때 JVM의 내부 버퍼를 이용하지 않고 직접 운영체제의 데이터를 접근해 속도 개선을 한 것이 NIO이다. 이를 사용해 파일을 쓰고 읽기를 사용법을 익혀보도록 하겠다. 


NIO를 이용한 파일 쓰고 일기의 3가지 클래스


nio를 사용 하기 위해서는 GatheringByteChannel, ScatteringByteChannel, ByteBuffer 3가지 클래스를 이용한다. 우선 전체 예제 부터 살펴 보겠다.


[전체 예제]

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.*;


public class ChannelFile {

public static void main(String[] args) {

try {

//NIO 함수를 이용해 파일 쓰기

FileOutputStream fo = new FileOutputStream("test.txt");

GatheringByteChannel gchannel = fo.getChannel();

ByteBuffer wheader = ByteBuffer.allocate(30);

ByteBuffer wbody = ByteBuffer.allocate(30);

ByteBuffer[] wbuffers = { wheader, wbody };

wheader.put("header is hello world".getBytes());

wbody.put("body is welcome to channel".getBytes());

wheader.flip();

wbody.flip();

gchannel.write(wbuffers);

gchannel.close();

//NIO 함수를 이용해 파일 읽기

FileInputStream fin = new FileInputStream("test.txt");

ScatteringByteChannel schannel = fin.getChannel();

ByteBuffer rheader = ByteBuffer.allocateDirect(10);

ByteBuffer rbody = ByteBuffer.allocateDirect(10);

ByteBuffer[] rbuffers = { rheader, rbody };

int readCount = (int) schannel.read(rbuffers);

System.out.println("cnt : " + readCount );

schannel.close();

rheader.flip();

rbody.flip();

byte[] byteHeaderBuffer = new byte[10];

byte[] byteBodyBuffer = new byte[10];

rheader.get(byteHeaderBuffer);

rbody.get(byteBodyBuffer);

System.out.println("header : " + new String(byteHeaderBuffer));

System.out.println("body : " + new String(byteBodyBuffer));

}catch( IOException e ) {

System.out.println(e);

}

}

}


[실행 결과]

cnt : 20

header : header is 

body : hello worl


[파일 쓰는 방법]

10자리 byte 만큼 메모리 공간 확보

//NIO 함수를 이용해 파일 쓰기


//디스크에 test.txt 파일을 만들어 채널 형식으로 변환한다.

FileOutputStream fo = new FileOutputStream("test.txt");

GatheringByteChannel gchannel = fo.getChannel();

//nio는 byte단위로만 사용할 수 있어 ByteBuffer형식으로 메모리를 생성한다.

ByteBuffer wheader = ByteBuffer.allocate(30);

ByteBuffer wbody = ByteBuffer.allocate(30);

ByteBuffer[] wbuffers = { wheader, wbody };

//생성한 메모리에 2군데에 각각 값을 입력한다.

wheader.put("header is hello world".getBytes());

wbody.put("body is welcome to channel".getBytes());

//메모리에 값을 입력하면 buffer가 가지고 있는 내부 position 값이 변해서 0으로 초기화 시킨다.

wheader.flip();

wbody.flip();

//채널 클래스로 디스크 파일에 직접 입력하고 닫는다.

gchannel.write(wbuffers);

gchannel.close();


[파일 읽는 방법]

position 0~2까지 순차적으로 데이터가 10, 11, 12를 넣는다. 이때 position의 위치도 바뀐다.

//디스크에 test.txt 파일을 읽고 채널 형식으로 변환한다.

FileInputStream fin = new FileInputStream("test.txt");

ScatteringByteChannel schannel = fin.getChannel();

//nio는 byte단위로만 사용할 수 있어 ByteBuffer형식으로 메모리를 생성한다.

ByteBuffer rheader = ByteBuffer.allocateDirect(10);

ByteBuffer rbody = ByteBuffer.allocateDirect(10);

ByteBuffer[] rbuffers = { rheader, rbody };

//파일의 내용을 채널을 통해 버퍼에 담는다.

int readCount = (int) schannel.read(rbuffers);

System.out.println("cnt : " + readCount );

schannel.close();

//각 데이터 버퍼의 positon 값이 변동 되어 0으로 초기화 한다.

rheader.flip();

rbody.flip();

//byte 버퍼로 부터 byte값을 얻어오기 위해 byte 형식으로 메모리 생성

byte[] byteHeaderBuffer = new byte[10];

byte[] byteBodyBuffer = new byte[10];

//각 버퍼에서 데이터를 얻어온다.

rheader.get(byteHeaderBuffer);

rbody.get(byteBodyBuffer);

//byte를 스트링 형식으로 변환해 출력한다.

System.out.println("header : " + new String(byteHeaderBuffer));

System.out.println("body : " + new String(byteBodyBuffer));



반응형

[Design Pattern] 싱글톤(Singleton) 패턴



프로그램 내에서 1개의 인스턴스만 생성 하기 위해서 필요한 것이 Singleton 패턴 입니다. 프로그램의 전역에서 사용될 설정 정보 값은 Singleton 패턴을 이용해 한개만 생성해 정보를 공유 하는데도 필요합니다. 사용자가 주의해서 1개만 생성하는것이 아닌 프로그램적으로 보증하는 방법을 제공해 줍니다.


싱글톤 패턴



싱글톤 패턴을 이용해 클래스를 만들어 보고 인스턴스가 1개 이상 생성되는지 확인해 보자.


[Singleton 구현]

싱글톤 클래스의 생성자는 private로 되어 있다. 이것은 싱글톤 클래스 외부에서 생성자를 호출을 금지하기 위해서다. 해당 패턴을 이용하면 프로그래머가 실수를 해도 인스턴스가 1개만 생성되도록 보증을 해주고 있다.


public class Singleton {

private static Singleton singleton = new Singleton();

private Singleton() {

System.out.println("인스턴스를 생성했습니다.");

}

public static Singleton getInstance() {

return singleton;

}

}



[Main 구현]


public class Main {

public static void main(String[] args) {

Singleton sing1 = Singleton.getInstance();

Singleton sing2 = Singleton.getInstance();

if ( sing1 == sing2 ) {

System.out.println("같은 인스턴스 입니다.");

} else {

System.out.println("다른 인스턴스 입니다.");

}

}

}



[실행 결과]


인스턴스를 생성했습니다.

같은 인스턴스 입니다.




실행 결과와 같이 sing1, sing2에서 2번 객체를 빼왔는데 인스턴스는 단 한번만 생성 된 것을 확인 할 수 있다.




반응형

'프로그램 > Design Pattern' 카테고리의 다른 글

[디자인패턴] Factory Method 패턴  (0) 2018.06.03
[디자인패턴] Template Method 패턴  (0) 2018.06.02
[디자인패턴] Adapter 패턴  (0) 2018.06.01
[디자인패턴] Iterator  (0) 2018.05.22

+ Recent posts