Java 바이트 버퍼에서 문자열로
이 방법으로 ByteBuffer를 String으로 변환하는 것이 올바른 접근 방식입니까?
String k = "abcd";
ByteBuffer b = ByteBuffer.wrap(k.getBytes());
String v = new String(b.array());
if(k.equals(v))
System.out.println("it worked");
else
System.out.println("did not work");
그 이유는 Java: ByteBuffer 및 관련 문제와의 변환과 같은 다른 접근법이 더 복잡해 보이기 때문입니다.
a there there there there 、 there 、 there 、 there 、 there 、 there 、 there 、 there 、 there 、 there there there there there there there there there there there 。ByteBuffer
String
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();
편집(2018):@xinyongCheng에 의해 편집된 형제답변은 더 단순한 접근법이며, 받아들여지는 답변이어야 합니다.
플랫폼의 기본 문자 집합에 바이트가 있다는 것을 알고 있다면 이 방법이 합리적입니다.예에서 인데, 왜냐하면 이 말이 맞다.k.getBytes()
플랫폼 기본 문자 집합의 바이트를 반환합니다.
인코딩을 지정하는 빈도가 높아집니다.그러나 링크한 질문보다 더 간단한 방법이 있습니다.String API는 특정 인코딩에서 String 배열과 byte[] 배열 사이를 변환하는 메서드를 제공합니다.이러한 방법에서는 "디코딩 [인코딩]프로세스에 대한 추가 제어가 필요한 경우" Charset Encoder/Charset Decoder 사용을 권장합니다.
특정 인코딩의 문자열에서 바이트를 가져오려면 형제 getBytes() 메서드를 사용합니다.
byte[] bytes = k.getBytes( StandardCharsets.UTF_8 );
특정 인코딩을 가진 바이트를 String에 넣으려면 다른 String 컨스트럭터를 사용합니다.
String v = new String( bytes, StandardCharsets.UTF_8 );
:ByteBuffer.array()
는 옵션 조작입니다.배열을 사용하여 ByteBuffer를 구성한 경우 해당 배열을 직접 사용할 수 있습니다.않으면 , 「」를 사용해 .ByteBuffer.get(byte[] dst, int offset, int length)
버퍼에서 바이트 배열로 바이트를 가져옵니다.
이것을 시험해 보세요.
new String(bytebuffer.array(), "ASCII");
주의: 인코딩을 모르면 바이트 배열을 문자열로 올바르게 변환할 수 없습니다.
이게 도움이 됐으면 좋겠다
ByteBuffer.array()가 항상 동작한다고 가정하는 것은 안전하지 않습니다.
byte[] bytes;
if(buffer.hasArray()) {
bytes = buffer.array();
} else {
bytes = new byte[buffer.remaining()];
buffer.get(bytes);
}
String v = new String(bytes, charset);
보통 buffer.hasArray()는 사용 사례에 따라 항상 true 또는 false입니다.실제로는 어떤 상황에서도 실제로 기능하는 것을 원하지 않는 한 불필요한 브랜치를 최적화하는 것이 안전합니다.그러나 나머지 응답은 ByteBuffer.allocateDirect()를 통해 작성된 ByteBuffer에서는 작동하지 않을 수 있습니다.
콜링(Calling)을 .array()
하지 않습니다('버퍼 사용'을할 수 .버퍼가 부분적으로 사용되고 있거나 어레이의 일부를 참조하고 있는 경우(이 경우,ByteBuffer.wrap
반드시 처음부터가 아닌 특정 오프셋의 배열)을 계산에서 고려해야 합니다.이것은, 모든 경우에 버퍼에 대해서 기능하는 일반적인 솔루션입니다(부호화에는 대응하지 않습니다).
if (myByteBuffer.hasArray()) {
return new String(myByteBuffer.array(),
myByteBuffer.arrayOffset() + myByteBuffer.position(),
myByteBuffer.remaining());
} else {
final byte[] b = new byte[myByteBuffer.remaining()];
myByteBuffer.duplicate().get(b);
return new String(b);
}
부호화와 관련된 문제는 Andy Thomas의 답변을 참조하십시오.
이 질문의 근원은 바이트를 문자열로 디코딩하는 방법입니다.
이것은, JAVA NIO CharSet 를 사용해 실행할 수 있습니다.
public final CharBuffer decode(ByteBuffer bb)
FileChannel channel = FileChannel.open(
Paths.get("files/text-latin1.txt", StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
CharSet latin1 = StandardCharsets.ISO_8859_1;
CharBuffer latin1Buffer = latin1.decode(buffer);
String result = new String(latin1Buffer.array());
- 먼저 채널을 생성하여 버퍼에서 읽습니다.
- 그런 다음 Latin1 버퍼를 char 버퍼로 디코딩합니다.
- 그런 다음 예를 들어 String에 결과를 넣을 수 있습니다.
Java를 사용하여 문자열을 ByteBuffer로 변환한 후 ByteBuffer에서 String으로 되돌립니다.
import java.nio.charset.Charset;
import java.nio.*;
String babel = "obufscate thdé alphebat and yolo!!";
System.out.println(babel);
//Convert string to ByteBuffer:
ByteBuffer babb = Charset.forName("UTF-8").encode(babel);
try{
//Convert ByteBuffer to String
System.out.println(new String(babb.array(), "UTF-8"));
}
catch(Exception e){
e.printStackTrace();
}
그러면 먼저 인쇄된 베어 문자열이 출력되고 다음으로 바이트 버퍼가 array()에 캐스트됩니다.
obufscate thdé alphebat and yolo!!
obufscate thdé alphebat and yolo!!
또한 문자열을 원시 바이트로 줄이면 무슨 일이 일어나고 있는지 확인하는 데 도움이 됩니다.
String text = "こんにちは";
//convert utf8 text to a byte array
byte[] array = text.getBytes("UTF-8");
//convert the byte array back to a string as UTF-8
String s = new String(array, Charset.forName("UTF-8"));
System.out.println(s);
//forcing strings encoded as UTF-8 as an incorrect encoding like
//say ISO-8859-1 causes strange and undefined behavior
String sISO = new String(array, Charset.forName("ISO-8859-1"));
System.out.println(sISO);
UTF-8로 해석된 문자열을 인쇄하고 ISO-8859-1로 다시 인쇄합니다.
こんにちは
ããã«ã¡ã¯
(부호화 문제와는 별도로) 링크되어 있는 보다 복잡한 코드 중 일부는 단순히 백업 어레이 전체의 모든 바이트를 부호화하는 것이 아니라 (예를 들어 위치와 제한을 사용하여) 문제의 바이트 버퍼의 "액티브" 부분을 얻는 문제가 발생한다는 점에 유의하십시오.
private String convertFrom(String lines, String from, String to) {
ByteBuffer bb = ByteBuffer.wrap(lines.getBytes());
CharBuffer cb = Charset.forName(to).decode(bb);
return new String(Charset.forName(from).encode(cb).array());
};
public Doit(){
String concatenatedLines = convertFrom(concatenatedLines, "CP1252", "UTF-8");
};
바이트 버퍼를 문자열로 변환하는 간단한 함수를 다음에 나타냅니다.
public String byteBufferToString(ByteBuffer bufferData) {
byte[] buffer = new byte[bufferData.readableByteCount()];
// read bufferData and insert into buffer
data.read(buffer);
// CharsetUtil supports UTF_16, ASCII, and many more
String text = new String(buffer, CharsetUtil.UTF_8);
System.out.println("Text: "+text);
return text;
}
이 방법만이 나에게 효과가 있었다.java.nio.ByteBuffer
인스턴스:
String fileContent = new String(bb.array(), StandardCharsets.UTF_8);
관련 코드 스니펫은 다음과 같습니다.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
Path path = Paths.get("/home/binita/testbb");
FileChannel fileChannel = FileChannel.open(path,
EnumSet.of(StandardOpenOption.READ
)
);
ByteBuffer bb = ByteBuffer.allocate(1024);
int bytesRead = fileChannel.read(bb);
if(bytesRead > 0) {
String fileContent = new String(bb.array(), StandardCharsets.UTF_8);
}
레퍼런스URL : https://stackoverflow.com/questions/17354891/java-bytebuffer-to-string
'programing' 카테고리의 다른 글
ReactJS 애플리케이션의 MVVM 아키텍처 패턴 (0) | 2023.02.10 |
---|---|
TypeScript / Angular에서 인터페이스 및 모델을 사용하는 경우 (0) | 2023.02.10 |
Python에서 두 목록을 연결하려면 어떻게 해야 하나요? (0) | 2023.02.06 |
MySQL RESTRICT와 No ACTION (0) | 2023.02.06 |
timedelta를 총 초수로 변환 (0) | 2023.02.06 |