java中的socket通信,怎么发送一个byte[]数组?

我是新手,最近开始看JAVA,看的那些范例都是:Stringmsg;PrintWriterout=newPrintWriter(socket.getOutputStrea... 我是新手,最近开始看JAVA,看的那些范例都是:
String msg;
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(msg);
就行了,但是老师好像说这是发送文本什么的,让我不要用PrintWriter,直接用outputstream来发送,于是我改成了:
byte[] b;
OutputStream out = socket.getOutputStream();
out.println(b);
可是这样子就显示说“println”有错误,具体是“The method println(byte[]) is undefined for the type OutputStream”
请问各位大神们,这是怎么回事?我写错了吗?应该改成什么样子?
展开
 我来答
198901245631
2015-06-26 · TA获得超过3.5万个赞
知道大有可为答主
回答量:9037
采纳率:92%
帮助的人:1663万
展开全部
socket发送的是流,所以必须将byte[]转换成流的形式,之后才可以发送的。创建socket后可以通过下面的方法实现发送:
PrintWriter pw = null;
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter( socket.getOutputStream()))); //创建一个输入流,之后这个流的指向是socket
pw.write(request.toString()); //写入要输入的Byte[],转换为字符串,之后进行传送
pw.close();//传送完毕,关闭流
bd9006
2012-05-15 · TA获得超过2.5万个赞
知道大有可为答主
回答量:4.8万
采纳率:63%
帮助的人:1.6亿
展开全部
java.lang.String
byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
byte[] getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated. This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset.
byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

java.io.OutputStream
void write(byte[] b)
Writes b.length bytes from the specified byte array to this output stream.
void write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this output stream.

LZ 应该学会看API。
追问
不好意思,我是菜鸟,你写的那些我看不懂,能更简单地讲一下吗?
追答
请不要用“菜鸟”来做借口。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
jwjy365
2012-05-15
知道答主
回答量:15
采纳率:0%
帮助的人:10万
展开全部
OutputStream 没有println(byte[])方法的,使用下面的方法写入
write(byte[] b)
将 b.length 个字节从指定的 byte 数组写入此输出流
另外建议你多看看java的API,这样的问题是直接可以从API上查到的
追问
这样子的啊,请问我这么写对不对:
byte[] b;
OutputStream out = socket.getOutputStream();
out.write(b);
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
csyangshungang
2012-05-15 · TA获得超过518个赞
知道小有建树答主
回答量:463
采纳率:0%
帮助的人:325万
展开全部
out.write(b);
out.flush();
这样 就把你要发送的数据发出去鸟
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
死神的飞刀
2012-05-15 · TA获得超过102个赞
知道答主
回答量:69
采纳率:0%
帮助的人:38.3万
展开全部
将out.println(b);
改成out.write(b);就行了
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(4)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式