![](/img/trans.png)
[英]DataInputStream and DataOutputStream: read and write several times
[英]DataInputStream and OutputStream write/read string with length
如何使用使用以下代碼存儲的DataInputStream
讀取String
:
DataOutputStream dataOut = new DataOutputStream (out); // Some other stream
String title = processed.getTitle();
dataOut.writeInt(title.length());
dataOut.writeBytes(title);
您可以像這樣閱讀。
DataInputStream dataIn = new DataInputStream (input);
int length = dataIn.readInt();
byte[] array = new byte[length];
dataIn.read(array);
您可以使用ByteArrayOutputStream
和ByteArrayInputStream
以及一個字節數組作為中間緩沖區。
ByteArrayOutputStream out = new ByteArrayOutputStream();
// Some other streams
DataOutputStream dataOut = new DataOutputStream (out);
String title = processed.getTitle();
dataOut.writeInt(title.length());
dataOut.writeBytes(title);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
DataInputStream dataIn = new DataInputStream(in);
dataOut.writeUTF(title);
// ...
String title = dataIn.readUTF();
...只要標題以這種格式編寫時不需要超過65533字節即可:請參閱Javadoc。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.