从InputStreamReader(JAVA)读取多行

发布于 2024-08-25 07:11:50 字数 86 浏览 1 评论 0原文

我有一个 InputStreamReader 对象。我想使用一个函数调用将多行读入缓冲区/数组(无需创建大量字符串对象)。有没有一种简单的方法可以做到这一点?

I have an InputStreamReader object. I want to read multiple lines into a buffer/array using one function call (without crating a mass of string objects). Is there a simple way to do so?

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

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

发布评论

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

评论(2

左秋 2024-09-01 07:11:50

首先要注意的是,InputStreamReader 效率不高,您应该将其包装在 BufferedReader 对象周围,以获得最大性能。

考虑到这一点,您可以执行以下操作:

public String readLines(InputStreamReader in)
{
  BufferedReader br = new BufferedReader(in);
  // you should estimate buffer size
  StringBuffer sb = new StringBuffer(5000);

  try
  {
    int linesPerRead = 100;
    for (int i = 0; i < linesPerRead; ++i)
    {
      sb.append(br.readLine());
      // placing newlines back because readLine() removes them
      sb.append('\n');
    }
  }
  catch (Exception e)
  {
    e.printStackTrace();
  }

  return sb.toString();
}

请注意,当达到 EOF 时,readLine() 返回 null,因此您应该检查并采取照顾它。

First of all mind that InputStreamReader is not so efficient, you should wrap it around a BufferedReader object for maximum performance.

Taken into account this you can do something like this:

public String readLines(InputStreamReader in)
{
  BufferedReader br = new BufferedReader(in);
  // you should estimate buffer size
  StringBuffer sb = new StringBuffer(5000);

  try
  {
    int linesPerRead = 100;
    for (int i = 0; i < linesPerRead; ++i)
    {
      sb.append(br.readLine());
      // placing newlines back because readLine() removes them
      sb.append('\n');
    }
  }
  catch (Exception e)
  {
    e.printStackTrace();
  }

  return sb.toString();
}

Mind that readLine() returns null is EOF is reached, so you should check and take care of it.

苄①跕圉湢 2024-09-01 07:11:50

如果您有多行有一些分隔符,您可以使用带有长度和偏移量的 read 方法读取那么多字符。否则,使用 StringBuilder 附加 BufferedReader 读取的每一行应该很适合您,而不会占用太多临时内存

If you have some delimiter for multiple lines you can read that many characters using read method with length and offset. Otherwise using a StringBuilder for appending each line read by BufferedReader should work well for you without eating up too much temp memory

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