需要评论关于java pushbackInpuStream代码转换为C#

时间:2011-11-05 16:49:58

标签: c# java inputstream

这是原始的java代码,它包含 PushbackInputStream

public String readLine(InputStream in) throws IOException
{
    char buf[] = new char[128];
    int offset = 0;
    int ch;

    for (;;)
    {
        ch = in.read();
        if (ch == -1 || ch == '\n')
        {
            break;
        }
        else if (ch == '\r')
        {
       int tmpch = in.read();
         if (tmpch != '\n')
         {
              if (! (in instanceof PushbackInputStream))PushbackInputStream))
              {
                in = new PushbackInputStream(in);
              }
                 ((PushbackInputStream) in).unread(tmpch);
          }
          break;
            }
        else
        {
        if (offset == buf.length)
        {
           char tmpbuf[] = buf;
           buf = new char[tmpbuf.length * 2];
           System.arraycopy(tmpbuf, 0, buf, 0, offset);
        }
          buf[offset++] = (char) ch;
        }
   }
     return String.copyValueOf(buf, 0, offset);
}

以下是我转换为C#的内容,我使用 StreamReader 类的 peek 方法实现了 PushbackInputstream ,但是有一个关键字我无法解释像instanceof。关键字“instanceof”在这种情况下是否重要?

    public String readLine(NetworkStream nsStream)
    {
        using (StreamReader reader = new StreamReader(nsStream))
        {
            char[] buffer = new char[128];
            int offset = 0;
            int ch;

            for (; ; )
            {
                ch = reader.Read();
                if (ch == -1 || ch == '\n')
                {
                    break;
                }
                else if (ch == '\r')
                {

                    if ((reader.Peek()) == '\n')
                    {
                        break;
                    }
                    else
                    {
                        reader.Read();
                    }
                }
                else
                {
                    if (offset == buffer.Length)
                    {
                        char[] tempBuffer = buffer;
                        buffer = new char[tempBuffer.Length * 2];
                        Array.Copy(tempBuffer, 0, buffer, 0, offset);
                    }
                    buffer[offset++] = (char)ch;
                }

            }
            return new string(buffer);
        }
    }

任何评论都将不胜感激!

1 个答案:

答案 0 :(得分:0)

您可以将网络流封装在StreamReader中并使用其Peek()方法:

using(StreamReader streamReader = new StreamReader(someNetworkStream))
{
     int nextChar = streamReader.Peek();
}