什么是outData.writeInt()在Java中做什么?
我是Java编程语言的新手,事实上我只有一些基本的编程概念。我遇到了下面这段Java代码,我无法理解那里的一个函数。如果有人向我解释'outData.writeInt()'做了什么以及如何使用它,我将不胜感激。谢谢。什么是outData.writeInt()在Java中做什么?
try {
if(moe.getSource() == forward)outData.writeInt(1);
if(moe.getSource() == reverse)outData.writeInt(2);
if(moe.getSource() == leftTurn)outData.writeInt(3);
if(moe.getSource() == rightTurn)outData.writeInt(4);
if(moe.getSource() == speedUp)outData.writeInt(6);
if(moe.getSource() == slowDown)outData.writeInt(7);
outData.flush();
}
catch (IOException ioe) {
System.out.println("\nIO Exception writeInt");
}
快速谷歌让我对DataOutputStream.writeInt()
商务部将int写入基础输出流为四个字节,高字节 第一。如果没有抛出异常,写的计数器由4
你DataOutputStream
将被写入文件,或者一个网络连接递增 。
虽然我同意,但这听起来更像是一条评论。 ;) – 2012-08-14 13:00:45
@ brian-agnew感谢您的快速回复。实际上面的代码是用Java编写的程序的一部分,程序可以与NXT Lego进行通信,并允许通过点击前进/后退/左/右按钮来控制它的移动。在这里,我真正想知道的是它是如何工作的,并且有没有其他选择? – 2012-08-14 13:18:15
writeInt()在DataOutputStream类
是记录将int写入基础输出流作为四个字节,高字节。如果没有抛出异常,则写入的计数器增加4.
简而言之,它会在big-endian中写入一个32位的int
值。
如果你想知道一个方法做什么,它很好的开始与源
/**
* Writes an <code>int</code> to the underlying output stream as four
* bytes, high byte first. If no exception is thrown, the counter
* <code>written</code> is incremented by <code>4</code>.
*
* @param v an <code>int</code> to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public final void writeInt(int v) throws IOException {
out.write((v >>> 24) & 0xFF);
out.write((v >>> 16) & 0xFF);
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
incCount(4);
}
有没有其他方法比这个更好?我们可以用其他函数替换outData.writeint。 – 2012-08-14 13:51:18
是的,如果您愿意,可以将每个字节写入一次或将两个16位值写入。 – 2012-08-14 13:52:09
好的...但我想知道它究竟做了什么?我想知道传递整数后会发生什么... – 2012-08-14 14:01:02
什么类outData是一个实例? – 2012-08-14 12:59:59