Java 将 OutputStream 转化为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/216894/
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-08-11 11:31:21  来源:igfitidea点击:

Get an OutputStream into a String

javastringiostream

提问by Adrian Mouat

What's the best way to pipe the output from an java.io.OutputStream to a String in Java?

将 java.io.OutputStream 的输出通过管道传输到 Java 中的字符串的最佳方法是什么?

Say I have the method:

说我有方法:

  writeToStream(Object o, OutputStream out)

Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.

它将某些数据从对象写入给定的流。但是,我想尽可能轻松地将此输出转换为字符串。

I'm considering writing a class like this (untested):

我正在考虑编写这样的类(未经测试):

class StringOutputStream extends OutputStream {

  StringBuilder mBuf;

  public void write(int byte) throws IOException {
    mBuf.append((char) byte);
  }

  public String getString() {
    return mBuf.toString();
  }
}

But is there a better way? I only want to run a test!

但是有更好的方法吗?我只想做个测试!

采纳答案by Horcrux7

I would use a ByteArrayOutputStream. And on finish you can call:

我会使用一个ByteArrayOutputStream. 完成后,您可以调用:

new String( baos.toByteArray(), codepage );

or better:

或更好:

baos.toString( codepage );

For the Stringconstructor, the codepagecan be a Stringor an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.

对于String构造函数,codepage可以是java.nio.charset.Charset 的一个String或一个实例。一个可能的值是java.nio.charset.StandardCharsets.UTF_8

The method toString()accepts only a Stringas a codepageparameter (stand Java 8).

该方法toString()只接受 aString作为codepage参数(支持 Java 8)。

回答by Joe Liversedge

I like the Apache Commons IO library. Take a look at its version of ByteArrayOutputStream, which has a toString(String enc)method as well as toByteArray(). Using existing and trusted components like the Commons project lets your code be smaller and easier to extend and repurpose.

我喜欢 Apache Commons IO 库。看看它的ByteArrayOutputStream版本,它有一个toString(String enc)方法以及toByteArray(). 使用现有的和受信任的组件(如 Commons 项目)可以让您的代码更小,更容易扩展和重新调整用途。

回答by Adrian Mouat

Here's what I ended up doing:

这是我最终做的:

Obj.writeToStream(toWrite, os);
try {
    String out = new String(os.toByteArray(), "UTF-8");
    assertTrue(out.contains("testString"));
} catch (UnsupportedEncondingException e) {
    fail("Caught exception: " + e.getMessage());
}

Where os is a ByteArrayOutputStream.

其中 os 是一个ByteArrayOutputStream.

回答by Adrian Mouat

This worked nicely

这很好用

OutputStream output = new OutputStream() {
    private StringBuilder string = new StringBuilder();

    @Override
    public void write(int b) throws IOException {
        this.string.append((char) b );
    }

    //Netbeans IDE automatically overrides this toString()
    public String toString() {
        return this.string.toString();
    }
};

method call =>> marshaller.marshal( (Object) toWrite , (OutputStream) output);

方法调用=>> marshaller.marshal( (Object) toWrite , (OutputStream) output);

then to print the string or get it just reference the "output" stream itself As an example, to print the string out to console =>> System.out.println(output);

然后打印字符串或获取它只是引用“输出”流本身作为示例,将字符串打印到控制台=>> System.out.println(output);

FYI: my method call marshaller.marshal(Object,Outputstream)is for working with XML. It is irrelevant to this topic.

仅供参考:我的方法调用marshaller.marshal(Object,Outputstream)用于处理 XML。它与本主题无关。

This is highly wasteful for productional use, there is a way too many conversion and it is a bit loose. This was just coded to prove to you that it is totally possible to create a custom OuputStream and output a string. But just go Horcrux7 way and all is good with merely two method calls.

这对于生产使用来说是非常浪费的,转换方式太多并且有点松散。这只是为了向您证明完全有可能创建自定义 OuputStream 并输出字符串。但是只要走 Horcrux7 的方式,只需两个方法调用就可以了。

And the world lives on another day....

而世界又活在另一天......

回答by jschnasse

baos.toString(StandardCharsets.UTF_8);

Converts the buffer's contents into a string by decoding the bytes using the named charset.

通过使用命名字符集对字节进行解码,将缓冲区的内容转换为字符串。

Java 14 - https://docs.oracle.com/

Java 14 - https://docs.oracle.com/