본문 바로가기

개발 Note/Android, Java,Kotlin

[Copy&Paste]String 다루기

반응형

 

byte[] to String

 byte[] ={'a','b',};
 String str = new String(data, StandardCharsets.UTF_8);
 
 
 
 byte[] ={'a','b',};
 String str = new String(data);

 

String.toCharArray()

 

String str = "abcdefg";
char [] array = str.toCharArray();

 

 

String.getBytes();

String str= "Hello";
byte buff[] = str.getBytes();
//charset
byte buff1[] = str.getBytes(StandardCharsets.UTF_8);

//charset string
try {
	byte buff2[] = str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
	e.printStackTrace();
}

 

byte[] to String

String str = "Hello";
byte buff[] = str.getBytes();
String str1 = new String(buff);

 

 

InputStream -> ByteArrayOutputStream -> String

(주로 File IO, Asset , network등 이용하는 경우 많이 사용하게 됨.)

 

InputStream input = this.getContext().getAssets().open("mytextfile.txt");

try {
	ByteArrayOutputStream result = new ByteArrayOutputStream();

	byte buff[] = new byte[1024];
	int length;
	while( (length = input.read(buff,0, 1024)) != -1){
		result.write(buff,0,length);
	}
	String str = result.toString("UTF-8");

} catch (IOException e) {
	e.printStackTrace();
}