java PrintWriter 和 byte[] 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6898469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:49:45  来源:igfitidea点击:

PrintWriter and byte[] problem

java

提问by senzacionale

byte[] data = (byte[])opBinding.execute();
PrintWriter out = new PrintWriter(outputStream);    
out.println(data);
out.flush();
out.close(); 

but instead of text i get @84654. How can i add byte[] to PrintWriter? I need byte[] and not strinf becouse i have encoing problems with ?????

但我得到的不是文本而是@84654。如何将 byte[] 添加到 PrintWriter?我需要 byte[] 而不是 strinf 因为我有编码问题????

回答by Kal

You can use the outputstream directly to write the bytes.

您可以直接使用输出流来写入字节。

outputStream.write(byte[] b);

回答by Jon Skeet

PrintWriteris meant for textdata, not binarydata.

PrintWriter用于文本数据,而不是二进制数据。

It sounds like you should quite possibly be converting your byte[]to a String, and then writing that string out - assuming the PrintWriteryou're writing to uses an encoding which supports the characters you're interested in.

听起来您很可能应该将您的转换byte[]为 a String,然后将该字符串写出 - 假设PrintWriter您要写入的对象使用支持您感兴趣的字符的编码。

You'll also need to know the encoding that the original text data has been encoded in for the byte[], in order to successfully convert to text to start with.

您还需要知道原始文本数据已为 编码的编码byte[],以便成功转换为文本以开始。

回答by nfechner

The problem is, that your code calls (implicitly) data.toString()before returning the result to your printlnstatement.

问题是,您的代码data.toString()在将结果返回到您的println语句之前调用(隐式)。

回答by Pratik

try this

试试这个

byte[] data = (byte[])opBinding.execute();
PrintWriter out = new PrintWriter(outputStream);    
out.println(new String(data));
out.flush();
out.close(); 

回答by Sathyan

It worked for me.. when i used

它对我有用..当我使用

PrintWriter out=new PrintWriter(System.out);

Also it converts the byte data to String using toString()method.. So it may be a reason for your encoding problem

它还使用toString()方法将字节数据转换为字符串..所以这可能是您编码问题的原因