다음 테스트 코드가 있습니다. 내가 어떻게 넣을 수 있고, 자바 NIO ByteBuffer를 사용하여 String을 얻을 수 있는지 알고 싶다. 도움이 필요한 곳에 두 가지 의견을 추가했습니다. 그래서Java NIO ByteBuffer : 문자열 넣기 및 가져 오기
You ordered 12 units of ????
[...]
하고 :
package testPipe;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class TestMemBuff {
static final String dataFile = "invoicedata";
static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
static final int[] units = { 12, 8, 13, 29, 50 };
static final String[] descs = { "Java T-shirt", "Java Mug",
"Duke Juggling Dolls", "Java Pin", "Java Key Chain" };
public static Charset charset = Charset.forName("UTF-8");
public static CharsetEncoder encoder = charset.newEncoder();
public static CharsetDecoder decoder = charset.newDecoder();
public static void main(String[] args) throws UnsupportedEncodingException {
double price;
int unit;
String desc;
double total = 0.0;
ByteBuffer buf = ByteBuffer.allocate(1024);
for (int i = 0; i < prices.length; i++) {
buf.putDouble(prices[i]);
buf.putInt(units[i]);
buf.asCharBuffer().put(descs[i]); // Is it correct?
}
buf.flip();
// INPUT
while (buf.hasRemaining()) {
price = buf.getDouble();
unit = buf.getInt();
desc = buf.asCharBuffer().toString(); //This must be wrong!
System.out.format("You ordered %d" + " units of %s at $%.2f%n",
unit, desc, price);
total += unit * price;
}
}
}
이
는 그것을 실행할 출력한다. 관심
실제로'???? '를 인쇄합니까? 'toString'은 무엇을합니까? –
예. 인코딩/디코딩에 문제가있을 것입니다. – user3727540