在Java中,如何使用Google的guava CharStreams.toString进程中的inputStream?

发布于 2024-11-29 06:38:01 字数 592 浏览 2 评论 0原文

我正在执行一个进程,并希望将其输出读入字符串中。我希望使用 Guava CharStreams.toString(InputSupplier供应商)。不幸的是,Process的getInputStream()返回的流是InputStream类型,而不是InputSupplier。我如何使用它来创建一个 InputSupplier 以与 toString() 一起使用?

理想情况下我可以做这样的事情:

CharStreams.toString(CharStreams.newReaderSupplier(process.getInputStream()))

但是你不能从InputStream构造一个InputSupplier,而且我很难找到如何做到这一点。

I am executing a process and want to read in its output into a String. Rather than deal with try/catch/finally, I am hoping to use the Guava CharStreams.toString(InputSupplier<R> supplier). Unfortunately, the stream returned by Process's getInputStream() is type InputStream and not InputSupplier. How can I use this to create an InputSupplier for use with toString()?

Ideally I could do something like this:

CharStreams.toString(CharStreams.newReaderSupplier(process.getInputStream()))

But you cannot construct an InputSupplier from an InputStream and I am having trouble finding out how to do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

空宴 2024-12-06 06:38:02

我还没有找到用番石榴做到这一点的方法。我相信开发商这样做是有充分理由的。在保持最小化的同时,我得到的最接近的是:

 CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
        @Override
        public InputStream getInput() throws IOException {
            return inputStream;
        }
    }, Charsets.UTF_16));

我使用了 CharStreams 中的 newReaderSupplier,因此您不必使用 InputStreamReader 包装它。

I haven't found a way to do this with guava yet. I am sure the developer has a good reason for this. The closest I have gotten without while keep it minimal is:

 CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
        @Override
        public InputStream getInput() throws IOException {
            return inputStream;
        }
    }, Charsets.UTF_16));

I have used newReaderSupplier from CharStreams so you don't have to wrap it with InputStreamReader.

忘你却要生生世世 2024-12-06 06:38:02

怎么样:

CharStreams.toString(new InputStreamReader(process.getInpusttream()))

它正在使用 CharStreams.toString(Readable)

What about this:

CharStreams.toString(new InputStreamReader(process.getInpusttream()))

It is using CharStreams.toString(Readable).

眼前雾蒙蒙 2024-12-06 06:38:02

到目前为止,这是我能做的最好的事情:

String commandOutput = CharStreams.toString(new InputSupplier<InputStreamReader>() {
    public InputStreamReader getInput() throws IOException {
        return new InputStreamReader(process.getInputStream());
    }
});

So far this is the best I could do:

String commandOutput = CharStreams.toString(new InputSupplier<InputStreamReader>() {
    public InputStreamReader getInput() throws IOException {
        return new InputStreamReader(process.getInputStream());
    }
});
吻安 2024-12-06 06:38:02

正确的做法——以及 Guava 试图促使你做的事情——是改变为你提供 InputStream 的代码,改为为你提供一个 InputSupplier。

这样做的原因是,这样,Guava 获取流,读取字符串,然后关闭它,并且在 Guava 关闭它之后你不会意外地使用它,因为你一开始就没有对 InputStream 的引用。这消除了很多潜在的错误。

另一个重载 CharStreams.toString(Readable) 不会关闭 Readable。如果您想拥有自己的特殊逻辑来关闭输入流,Guava 可以让您这样做。

Guava 相当于 IOUtils.toString(InputStream) 说得比我好可以。

The Right Thing to Do -- and what Guava's trying to push you into doing -- is to change the code that gives you the InputStream to give you an InputSupplier instead.

The reason for this is that this way, Guava gets the stream, reads the string, and closes it, and you can't accidentally use it after Guava's closed it, because you never had a reference to the InputStream in the first place. This eliminates a lot of potential bugs.

The other overload, CharStreams.toString(Readable), does not close the Readable. If you want to have your own, special logic for closing the input stream, this is Guava's way of letting you do that.

Guava equivalent for IOUtils.toString(InputStream) says it better than I could.

野心澎湃 2024-12-06 06:38:02

这应该可以做到:

InputStream is = process.getInputStream();
String content = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
is.close();

这是一个完整用法的现实例子:

HttpURLConnection connection = null;
URL url;
InputStream is = null;
try {
  url = new URL("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" + appSecret + "&grant_type=client_credentials");
  connection = (HttpURLConnection) url.openConnection();
  connection.setRequestProperty("accept-encoding", "gzip");

  is = connection.getInputStream();
  String content = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
  String[] tokens = content.split("=");
  System.out.println(tokens[1]);
} catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
} finally {
  if (is != null) try {
    is.close();
  } catch (IOException e) {}
  connection.disconnect();
}

我知道这并不是真正的问题,但为了比较,他就是你如何使用 IOUtils 做到这一点 - IMO 更干净一些:

HttpURLConnection connection = null;
URL url;
InputStream is = null;

try {
  url = new URL("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" + appSecret + "&grant_type=client_credentials");
  connection = (HttpURLConnection) url.openConnection();
  connection.setRequestProperty("accept-encoding", "gzip");

  is = connection.getInputStream();

  String value = IOUtils.toString(is);
  if (!Strings.isNullOrEmpty(value)) {
    String[] splits = value.split("=");
    System.out.println(splits[1]);
  }
} catch (IOException e) {

} finally {
  IOUtils.closeQuietly(is);
  connection.disconnect();
}

This should do it:

InputStream is = process.getInputStream();
String content = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
is.close();

And here is a real life example of the complete usage:

HttpURLConnection connection = null;
URL url;
InputStream is = null;
try {
  url = new URL("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" + appSecret + "&grant_type=client_credentials");
  connection = (HttpURLConnection) url.openConnection();
  connection.setRequestProperty("accept-encoding", "gzip");

  is = connection.getInputStream();
  String content = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
  String[] tokens = content.split("=");
  System.out.println(tokens[1]);
} catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
} finally {
  if (is != null) try {
    is.close();
  } catch (IOException e) {}
  connection.disconnect();
}

I know this insn't really in question, but for comparison sake he is how you'd do it with IOUtils - which IMO is a bit cleaner:

HttpURLConnection connection = null;
URL url;
InputStream is = null;

try {
  url = new URL("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" + appSecret + "&grant_type=client_credentials");
  connection = (HttpURLConnection) url.openConnection();
  connection.setRequestProperty("accept-encoding", "gzip");

  is = connection.getInputStream();

  String value = IOUtils.toString(is);
  if (!Strings.isNullOrEmpty(value)) {
    String[] splits = value.split("=");
    System.out.println(splits[1]);
  }
} catch (IOException e) {

} finally {
  IOUtils.closeQuietly(is);
  connection.disconnect();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文