-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathBufferedRandom.java
More file actions
100 lines (85 loc) · 2.16 KB
/
BufferedRandom.java
File metadata and controls
100 lines (85 loc) · 2.16 KB
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
/* Copyright (c) 2007 Jython Developers */
package org.python.core.io;
import java.nio.ByteBuffer;
/**
* A buffered reader and writer together for a random access file.
*
* @author Philip Jenvey
*/
public class BufferedRandom extends BufferedIOMixin {
/** The buffered reader */
protected BufferedIOBase reader;
/** The buffered writer */
protected BufferedIOBase writer;
/**
* Construct a BufferedRandom of bufferSize, wrapping the given
* RawIOBase.
*
* @param rawIO {@inheritDoc}
* @param bufferSize {@inheritDoc}
*/
public BufferedRandom(RawIOBase rawIO, int bufferSize) {
super(rawIO, bufferSize);
initChildBuffers();
}
/**
* Initialize the child read/write buffers.
*
*/
protected void initChildBuffers() {
this.reader = new BufferedReader(rawIO, bufferSize);
this.writer = new BufferedWriter(rawIO, bufferSize);
}
@Override
public long seek(long pos, int whence) {
flush();
// First do the raw seek, then empty the read buffer, so that
// if the raw seek fails, we don't lose buffered data forever.
pos = writer.seek(pos, whence);
reader.clear();
return pos;
}
@Override
public long tell() {
if (writer.buffered()) {
return writer.tell();
}
return reader.tell();
}
@Override
public ByteBuffer read(int size) {
flush();
return reader.read(size);
}
@Override
public ByteBuffer readall() {
flush();
return reader.readall();
}
@Override
public int readinto(ByteBuffer bytes) {
flush();
return reader.readinto(bytes);
}
@Override
public int write(ByteBuffer bytes) {
if (reader.buffered()) {
reader.clear();
}
return writer.write(bytes);
}
@Override
public ByteBuffer peek(int size) {
flush();
return reader.peek(size);
}
@Override
public int read1(ByteBuffer bytes) {
flush();
return reader.read1(bytes);
}
@Override
public void flush() {
writer.flush();
}
}