本文整理匯總了Java中java.nio.channels.SeekableByteChannel類的典型用法代碼示例。如果您正苦於以下問題:Java SeekableByteChannel類的具體用法?Java SeekableByteChannel怎麽用?Java SeekableByteChannel使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
SeekableByteChannel類屬於java.nio.channels包,在下文中一共展示了SeekableByteChannel類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: readBytes
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
/**
*
*/
public static byte[] readBytes(File file) throws IOException {
if (file != null) {
long fileSize = file.length();
if (fileSize > MAX_ARRAY_SIZE) {
throw new IOException("file is too large");
}
try (SeekableByteChannel byteChannel = Files.newByteChannel(file.toPath());
InputStream inputStream = Channels.newInputStream(byteChannel)) {
int available = inputStream.available();
if (available > 0) {
return readBytes(inputStream,available > fileSize ?
available : (int)fileSize);
}
}
}
return EMPTY_BYTE_ARRAY;
}
示例2: main
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.home") + "/test/myfile.txt");
try (SeekableByteChannel sbc = Files.newByteChannel(file)) { // |\longremark{newByteChannel默認返回隻讀的Channel}|
ByteBuffer buf = ByteBuffer.allocate(10); // |\longremark{allocate創建一個指定字節的ByteBuffer,本例中,sbc這個Channel每次讀取10個字節}|
String encoding = System.getProperty("file.encoding"); // |\longremark{獲得當前係統文件編碼方式,以便讀取文件字節後解碼}|
while (sbc.read(buf) > 0) { // |\longremark{從通道讀數據到緩衝區}|
buf.flip(); // |\longremark{切換緩衝區為讀模式}|
System.out.print(Charset.forName(encoding).decode(buf));
buf.clear(); // |\longremark{清空緩衝區,準備寫入下一輪數據}|
}
} catch (IOException x) {
System.out.println("caught exception: " + x);
}
}
示例3: hash
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
private static byte[] hash(Path path) throws IOException {
TlData tlData = InputFile.tlData.get();
MessageDigest digest = tlData.digest;
ByteBuffer buffer = tlData.buffer;
buffer.clear();
try (SeekableByteChannel channel = Files.newByteChannel(path)) {
while (channel.read(buffer) != -1) {
buffer.flip();
digest.update(buffer);
buffer.clear();
}
}
return digest.digest();
}
示例4: readStringWithLength
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
/**
* Reads an LC style string from a channel, which is a int32 length
* plus a UTF-8 encoded string possibly ends with \0.
* @throws IOException if there is a format error
* @throws BufferUnderflowException if goes beyond the end
*/
private static String readStringWithLength(SeekableByteChannel chan)
throws IOException {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.nativeOrder());
chan.read(bb);
bb.flip();
int len = bb.getInt();
if (len > 1024) {
// Memory attack? The string should be fairly short.
throw new IOException("Invalid string length");
}
bb = ByteBuffer.allocate(len);
if (chan.read(bb) != len) {
throw new IOException("Not enough string");
}
byte[] data = bb.array();
return (data[len-1] == 0)?
new String(data, 0, len-1, StandardCharsets.UTF_8):
new String(data, StandardCharsets.UTF_8);
}
示例5: newZipFile
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
@Override
protected ZipFile newZipFile(final SeekableByteChannel sbc)
throws IOException {
final RaesReadOnlyChannel rroc = RaesReadOnlyChannel.create(
raesParameters, new OneTimeSource(sbc));
try {
if (rroc.size() < AUTHENTICATION_TRIGGER) // heuristic
rroc.authenticate();
return new ZipFile(rroc);
} catch (final Throwable ex) {
try {
rroc.close();
} catch (final IOException ex2) {
ex.addSuppressed(ex2);
}
throw ex;
}
}
示例6: expunge
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
private static void expunge(Path p, KerberosTime currTime)
throws IOException {
Path p2 = Files.createTempFile(p.getParent(), "rcache", null);
try (SeekableByteChannel oldChan = Files.newByteChannel(p);
SeekableByteChannel newChan = createNoClose(p2)) {
long timeLimit = currTime.getSeconds() - readHeader(oldChan);
while (true) {
try {
AuthTime at = AuthTime.readFrom(oldChan);
if (at.ctime > timeLimit) {
ByteBuffer bb = ByteBuffer.wrap(at.encode(true));
newChan.write(bb);
}
} catch (BufferUnderflowException e) {
break;
}
}
}
makeMine(p2);
Files.move(p2, p,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
}
示例7: create
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
/**
* Creates a new RAES read-only channel.
*
* @param param the {@link RaesParameters} required to access the RAES
* type actually found in the file.
* If the class of this parameter does not match the required
* parameter interface according to the RAES type found in the
* file, but is an instance of the {@link RaesParametersProvider}
* interface, then it gets queried to find the required RAES
* parameters.
* This algorithm gets recursively applied.
* @param channel the channel for reading the RAES file from.
* @return A new RAES read-only channel.
* @throws RaesParametersException If no RAES parameter can be found which
* match the type of RAES file in the given channel.
* @throws RaesException If the source data is not RAES compatible.
* @throws EOFException on unexpected end-of-file.
* @throws IOException on any I/O error.
*/
@CreatesObligation
private static RaesReadOnlyChannel create(
final RaesParameters param,
final @WillCloseWhenClosed SeekableByteChannel channel)
throws RaesParametersException, RaesException, EOFException, IOException {
final PowerBuffer header = PowerBuffer
.allocate(HEADER_MIN_LEN)
.littleEndian()
.load(channel.position(0));
if (SIGNATURE != header.getUInt())
throw new RaesException("No RAES signature!");
final int type = header.getUByte();
switch (type) {
case 0:
return new Type0RaesReadOnlyChannel(
parameters(Type0RaesParameters.class, param),
channel);
default:
throw new RaesException("Unknown RAES type: " + type);
}
}
示例8: channel
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
@Override
public SeekableByteChannel channel(final OutputSocket<? extends Entry> peer)
throws IOException {
final IoBuffer buffer = entry.getPool().allocate();
try {
IoSockets.copy(entry.input(), buffer.output());
} catch (final Throwable ex) {
try {
buffer.release();
} catch (final Throwable ex2) {
ex.addSuppressed(ex2);
}
throw ex;
}
final class BufferReadOnlyChannel extends ReadOnlyChannel {
boolean closed;
@CreatesObligation
BufferReadOnlyChannel() throws IOException {
super(buffer.input().channel(peer)); // or .channel(null)
}
@Override
public void close() throws IOException {
if (!closed) {
channel.close();
closed = true;
buffer.release();
}
}
}
return new BufferReadOnlyChannel();
}
示例9: parseDatHeader
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
private void parseDatHeader() throws IOException {
if (parsed) return;
try (SeekableByteChannel channel = Files.newByteChannel(datFile)) {
channel.position(Math.abs(position));
CountingStream countingStream = new CountingStream(new BufferedInputStream(Channels.newInputStream(channel)), Long.MAX_VALUE);
DataInputStream stream = new DataInputStream(countingStream);
String status = readString(stream);
String size = readString(stream);
String msg = readString(stream);
String contentType = readString(stream);
String lastModified = readString(stream);
String etag = readString(stream);
for (;;) {
String line = readString(stream);
if (line.equals("HTS")) break;
if (line.equals("SD")) {
readString(stream); // supplementary data
}
}
dataLen = Long.parseLong(readString(stream));
headerLen = countingStream.count;
parsed = true;
}
}
示例10: read
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
ByteString read(CheckedFunction<Path, Path, IOException> resolver, long offset, long length)
throws IOException {
flush();
if (offset + length > getSize()) {
throw new IOException("Failed to read: offset (=" + offset
+ " + length (=" + length + ") > size = " + getSize()
+ ", path=" + getRelativePath());
}
try(final SeekableByteChannel in = Files.newByteChannel(
resolver.apply(getRelativePath()), StandardOpenOption.READ)) {
final ByteBuffer buffer = ByteBuffer.allocateDirect(FileStoreCommon.getChunkSize(length));
in.position(offset).read(buffer);
buffer.flip();
return ByteString.copyFrom(buffer);
}
}
示例11: ioResourceToByteBuffer
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
ByteBuffer buffer;
Path path = Paths.get(resource);
if(Files.isReadable(path)) {
try(SeekableByteChannel fc = Files.newByteChannel(path)){
buffer = BufferUtils.createByteBuffer((int)fc.size() + 1);
while(fc.read(buffer) != -1);
}
}else{
try(InputStream source = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
ReadableByteChannel rbc = Channels.newChannel(source)){
buffer = BufferUtils.createByteBuffer(bufferSize);
while(true){
int bytes = rbc.read(buffer);
if(bytes == -1)
break;
if (buffer.remaining() == 0)
buffer = resizeBuffer(buffer, buffer.capacity() * 2);
}
}
}
buffer.flip();
return buffer;
}
示例12: readFromFile
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
public static List<BinaryTrade> readFromFile(Path p) throws IOException {
System.out.println("Reading binary data to file ... ");
List<BinaryTrade> trades = new ArrayList<>();
long start = System.nanoTime();
try (SeekableByteChannel channel = Files.newByteChannel(p, READ)) {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(batchSize);
int nRead;
while ((nRead = channel.read(byteBuffer)) != -1) {
if (nRead == 0) continue;
byteBuffer.position(0);
byteBuffer.limit(nRead);
while (byteBuffer.hasRemaining()) {
byte[] bytes = new byte[40];
byteBuffer.get(bytes, 0, 40);
trades.add(new BinaryTrade(bytes));
}
byteBuffer.clear();
}
}
System.out.printf("\tTime to read %,.1f million elements: %,.2f seconds%n%n", trades.size() / 1e6, (System.nanoTime() - start) / 1e9);
return trades;
}
示例13: LineReader
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
public LineReader(final ReadableByteChannel channel)
throws IOException {
buf = ByteBuffer.allocate(BUF_SIZE);
buf.flip();
boolean removeLine = false;
// If we are not at the beginning of a line, we should ignore the current line.
if (channel instanceof SeekableByteChannel) {
SeekableByteChannel seekChannel = (SeekableByteChannel) channel;
if (seekChannel.position() > 0) {
// Start from one character back and read till we find a new line.
seekChannel.position(seekChannel.position() - 1);
removeLine = true;
}
nextLineStart = seekChannel.position();
}
this.channel = channel;
if (removeLine) {
nextLineStart += readNextLine(new ByteArrayOutputStream());
}
}
示例14: csize
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
private static int csize(int p) throws Exception {
try (SeekableByteChannel chan = Files.newByteChannel(
Paths.get(cwd, dfl(p)), StandardOpenOption.READ)) {
chan.position(6);
int cc = 0;
while (true) {
try {
if (AuthTime.readFrom(chan) != null) cc++;
} catch (BufferUnderflowException e) {
break;
}
}
return cc;
} catch (IOException ioe) {
return 0;
}
}
示例15: csize
import java.nio.channels.SeekableByteChannel; //導入依賴的package包/類
private static int csize(int p) throws Exception {
try (SeekableByteChannel chan = Files.newByteChannel(
Paths.get(dfl(p)), StandardOpenOption.READ)) {
chan.position(6);
int cc = 0;
while (true) {
try {
if (AuthTime.readFrom(chan) != null) cc++;
} catch (BufferUnderflowException e) {
break;
}
}
return cc;
} catch (IOException ioe) {
return 0;
}
}