如何阅读String
,DataInputStream
使用此代码存储:
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
andByteArrayInputStream
和一个字节数组作为中间缓冲区..
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。