2011-05-28 139 views
0

我寫過一個叫LimitedInputStream的課。它包裝現有的輸入流以將從中讀取的字節數限制爲指定的長度。這意味着作爲替代:這個LimitedInputStream是否正確?

byte[] data = readAll(length); 
InputStream ins = new ByteArrayInputStream(data); 

這需要額外的緩衝區。

這是類:

public static class LimitedInputStream extends InputStream { 
    private final InputStream ins; 
    private int left; 
    private int mark = -1; 

    public LimitedInputStream(InputStream ins, int limit) { 
     this.ins = ins; 
     left = limit; 
    } 

    public void skipRest() throws IOException { 
     ByteStreams.skipFully(ins, left); 
     left = 0; 
    } 

    @Override 
    public int read() throws IOException { 
     if (left == 0) return -1; 
     final int read = ins.read(); 
     if (read > 0) left--; 
     return read; 
    } 

    @Override 
    public int read(byte[] b, int off, int len) throws IOException { 
     if (left == 0) return -1; 
     if (len > left) len = left; 
     final int read = ins.read(b, off, len); 
     if (read > 0) left -= read; 
     return read; 
    } 

    @Override 
    public int available() throws IOException { 
     final int a = ins.available(); 
     return a > left ? left : a; 
    } 

    @Override 
    public void mark(int readlimit) { 
     ins.mark(readlimit); 
     mark = left; 
    } 

    @Override 
    public void reset() throws IOException { 
     if (!ins.markSupported()) throw new IOException("Mark not supported"); 
     if (mark == -1) throw new IOException("Mark not set"); 

     ins.reset(); 
     left = mark; 
    } 

    @Override 
    public long skip(long n) throws IOException { 
     if (n > left) n = left; 
     long skipped = ins.skip(n); 
     left -= skipped; 
     return skipped; 
    } 

} 

使用案例:

Object readObj() throws IOException { 
    int len = readInt(); 
    final LimitedInputStream lis = new LimitedInputStream(this, len); 
    try { 
     return deserialize(new CompactInputStream(lis)); 
    } finally { 
     lis.skipRest(); 
    } 
} 

for (something) { 
    Object obj; 
try { 
    obj = readObj(); 
} catch (Exception e) { 
    obj = null; 
} 
list.add(obj); 
} 

莫非你的代碼審查我的課堂任何嚴重的錯誤,例如更新left時可能出現的錯誤?

+2

1. http://codereview.stackexchange.com 2.單元測試是你的朋友! – 2011-05-28 15:32:53

回答

1

番石榴包括一個LimitInputStream,所以你可能只想使用它。

+0

它沒有像我的'skipRest'這樣的方法,這是必需的,但是看它的源代碼確實指向我自己的一些錯誤。 – 2011-05-28 16:06:19