blob: deb805eedf2489e7e3a1a1fb1453cf7126ea2615 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
/*
* Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eike Stepper - initial API and implementation
*/
package org.eclipse.net4j.util.io;
import java.io.IOException;
import java.io.Reader;
/**
* @author Eike Stepper
* @since 3.1
*/
public class LimitedReader extends Reader
{
private Reader in;
private long remaining;
private long remainingAtMark = 0;
public LimitedReader(Reader in, long length)
{
this.in = in;
remaining = length;
}
@Override
public int read() throws IOException
{
if ((remaining -= 1) < 0)
{
return -1;
}
return in.read();
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException
{
if (remaining <= 0)
{
return -1;
}
if (len > remaining)
{
len = (int)remaining;
}
len = in.read(cbuf, off, len);
if (len > 0)
{
remaining -= len;
}
else
{
remaining -= remaining;
}
return len;
}
@Override
public long skip(long n) throws IOException
{
if (n > remaining)
{
n = remaining;
}
remaining -= n = in.skip(n);
return n;
}
@Override
public boolean markSupported()
{
return in.markSupported();
}
@Override
public void mark(int readlimit) throws IOException
{
if (markSupported())
{
in.mark(readlimit);
remainingAtMark = remaining;
}
}
@Override
public void reset() throws IOException
{
in.reset();
remaining = remainingAtMark;
}
@Override
public void close() throws IOException
{
remaining = 0;
in.close();
}
}
|