在我正在为大学工作的这个 Java 项目中,我有一种情况,我目前正在使用
通过网络成功发送字符串streamOut = ObjectOutputStream
streamIn = ObjectInputStream
streamOut.writeUTF(msgs.peek());
其中 msgs 是一个链接的阻塞队列,用
接收它String in = streamIn.readUTF();
但是,我想使用 ObjectInputStream 和 ObjectOutputStream。我已经在构造函数中对它们进行了初始化,并且在构造它之后刷新了 ObjectOutputStream,我在某处读到你必须这样做。
我想同时发送字符串和另一种对象类型,通过网络将其称为游戏世界(此时不关心效率)..但是当我这样做时
streamOut.writeObject("mad cuz i'm bad");
Object in = streamIn.readObject();
if(in instanceof String) String inS = (String) in;
当我发送字符串时它没有接收到任何信息......我的 friend 正在做同一个项目并且他只传递一种类型的对象,这个对象的一个子类本质上是一个字符串和他的版本工作正常,但他在线程运行循环的每次迭代中都创建了一个新流。
我是否需要对流做一些事情来接收除 Object 之外没有共同祖先的不同对象,我是否需要在运行循环的每次迭代中创建一个新流,或者是否有其他完全相同的东西我失踪了,我提供的信息不足以说明哪里出了问题?
最佳答案
将字符串作为原始数据或作为对象写入流中存在显着差异。 writeObject 写入的 String 实例最初作为 String 写入流中。 future 的 writeObject() 调用将对字符串的引用写入流中。
例如
ByteArrayOutputStream baos1=new ByteArrayOutputStream();
oos1=new ObjectOutputStream(baos1);
baos2=new ByteArrayOutputStream();
ObjectOutputStream oos2=new ObjectOutputStream(baos2);
String testString="First";
oos1.writeObject(testString);
oos2.writeUTF(testString);
testString="Second";
oos1.writeObject(testString);
oos2.writeUTF(testString);
testString="Third";
oos1.writeObject(testString);
oos2.writeUTF(testString);
oos1.flush();
oos2.flush();
byte[] byteArray1=baos1.toByteArray();
byte[] byteArray2=baos2.toByteArray();
转储最后两个数组你会得到这样的结果:
writeObject 即 byteArray1
二进制:-84 -19 0 5 116 0 5 70 105 114 115 116 116 0 6 83 101 99 111 110 100 116 0 5 84 104 105 114 100
ASCII:-T - t F i r s t t S e c o n d t T h i r d
writeUTF 即 byteArray2
二进制:-84 -19 0 5 119 22 0 5 70 105 114 115 116 0 6 83 101 99 111 110 100 0 5 84 104 105 114 100
ASCII:-T - w F i r s t S e c o n d T h i r d
结论:在 writeObject 的情况下,一个额外的数据(这里是 t)被流式传输,而在 writeUTF 的情况下,只有字符串数据被流式传输。
更多信息:http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#writeUTF(java.lang.String)
关于java - writeUTF(String s) 与 writeObject(String s),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19269688/