当前位置: 首页>>代码示例>>Java>>正文


Java SeekableByteChannel类代码示例

本文整理汇总了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;
}
 
开发者ID:annoflex,项目名称:annoflex,代码行数:26,代码来源:SystemToolkit.java

示例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);
    }
}
 
开发者ID:subaochen,项目名称:java-tutorial,代码行数:17,代码来源:FileChannelTest.java

示例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();
}
 
开发者ID:sfPlayer1,项目名称:Matcher,代码行数:18,代码来源:InputFile.java

示例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);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:27,代码来源:AuthTime.java

示例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;
    }
}
 
开发者ID:christian-schlichtherle,项目名称:truevfs,代码行数:19,代码来源:ZipRaesIT.java

示例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);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:24,代码来源:DflCache.java

示例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);
    }
}
 
开发者ID:christian-schlichtherle,项目名称:truevfs,代码行数:41,代码来源:RaesReadOnlyChannel.java

示例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();
}
 
开发者ID:christian-schlichtherle,项目名称:truevfs,代码行数:34,代码来源:HttpInputSocket.java

示例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;
    }
}
 
开发者ID:nla,项目名称:httrack2warc,代码行数:27,代码来源:NdxCache.java

示例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);
  }
}
 
开发者ID:apache,项目名称:incubator-ratis,代码行数:18,代码来源:FileInfo.java

示例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;
}
 
开发者ID:tek256,项目名称:LD38,代码行数:27,代码来源:Util.java

示例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;
}
 
开发者ID:kogupta,项目名称:scala-playground,代码行数:25,代码来源:FilePersister.java

示例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());
    }
}
 
开发者ID:obradovicluka,项目名称:dataflow-playground,代码行数:23,代码来源:CsvWithHeaderFileSource.java

示例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;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:ReplayCacheTestProc.java

示例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;
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:18,代码来源:ReplayCacheTestProc.java


注:本文中的java.nio.channels.SeekableByteChannel类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。