Java 帮助:字符编码帮助 - int 到 String
我正在尝试使用 java.io.OutputStream 的 write(int) 方法,但我不知道如何正确地将 int 转换回 String 。
public PrintWriter out = new PrintWriter(new OutputStream() {
@Override
public void write(int b) throws IOException {
outputField.setText(/* I need a byte[] or char[] or string from this int */);
}
});
我真的需要这方面的帮助。我尝试使用一种方法从 int 生成 byte[],但它使文本因大量空格而变得混乱。
I am trying to use the write(int) method of java.io.OutputStream, and I can't figure out how to convert the int back into a String correctly.
public PrintWriter out = new PrintWriter(new OutputStream() {
@Override
public void write(int b) throws IOException {
outputField.setText(/* I need a byte[] or char[] or string from this int */);
}
});
I really need assistance with this. I tried to use a method to make a byte[] from an int but it made the text messed up with lots of spaces.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你试过这个
或
Have you tried this
or
将 OutputStream 定向到某种 GUI 中的文本字段似乎很奇怪。你确定这就是你真正想要的吗?如果您想捕获正在写入 Writer 的内容,请使用 StringWriter 通常是合适的。您只需让写入发生,然后调用 toString() 即可得到最终结果。如果您确实正在寻找一种将内容写入文本字段的方法,就像写入 Writer/OutputStream 一样,请查看以下内容:
注释 1:使用正确的编码代替 UTF-8。
注 2:虽然我使用 Thread.sleep() 减慢了速度,但一次向字段写入一个字符本身有些浪费,因为您不断地创建和丢弃字符串。做一些少量的缓冲,就像我之前提到的使用 StringWriter ,可能是一个更好的方法,除非您追求读入内容时出现的“实时反馈”感觉。
It seems very odd to be directing an OutputStream to what appears to be a text field in a GUI of some kind. Are you sure that's what you really want? If you want to capture something being written to a Writer, a StringWriter is usually appropriate. You just let the writing happen, then call toString() on it to get the final result. If you really are looking for a way to write stuff to a text field as it's written to a Writer/OutputStream, then check this out:
Note 1: Use the right encoding in place of UTF-8.
Note 2: While I slowed this down with a Thread.sleep(), writing a character at a time to a field is somewhat wasteful in itself because you're constantly creating and throwing away Strings. Doing some small amount of buffering, like using a StringWriter as I mentioned earlier, might be a better approach unless you're after the "live feed" feel of having stuff appear as it's read in.