java.nio.channels.Channels.newInputStream()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(9.7k)|赞(0)|评价(0)|浏览(280)

本文整理了Java中java.nio.channels.Channels.newInputStream()方法的一些代码示例,展示了Channels.newInputStream()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Channels.newInputStream()方法的具体详情如下:
包路径:java.nio.channels.Channels
类名称:Channels
方法名:newInputStream

Channels.newInputStream介绍

[英]Returns an input stream on the given channel. The resulting stream has the following properties:

  • If the stream is closed, then the underlying channel is closed as well.
  • It is thread safe.
  • It throws an IllegalBlockingModeException if the channel is in non-blocking mode and read is called.
  • Neither mark nor reset is supported.
  • It is not buffered.
    [中]返回给定通道上的输入流。结果流具有以下属性:
    *如果流已关闭,则基础通道也将关闭。
    *它是线程安全的。
    *如果通道处于非阻塞模式并且调用了read,则会抛出非法阻塞模式异常。
    *不支持标记或重置。
    *它没有缓冲。

代码示例

代码示例来源:origin: stackoverflow.com

FileChannel fc = ...
GZIPInputStream gis = new GZIPInputStream(Channels.newInputStream(fc));

代码示例来源:origin: GoogleContainerTools/jib

/**
 * Deserializes a JSON file via a JSON object template with a shared lock on the file
 *
 * @param <T> child type of {@link JsonTemplate}
 * @param jsonFile a file containing a JSON string
 * @param templateClass the template to deserialize the string to
 * @return the template filled with the values parsed from {@code jsonFile}
 * @throws IOException if an error occurred during reading the file or parsing the JSON
 */
public static <T extends JsonTemplate> T readJsonFromFileWithLock(
  Path jsonFile, Class<T> templateClass) throws IOException {
 // channel is closed by inputStream.close()
 FileChannel channel = FileChannel.open(jsonFile, StandardOpenOption.READ);
 channel.lock(0, Long.MAX_VALUE, true); // shared lock, released by channel close
 try (InputStream inputStream = Channels.newInputStream(channel)) {
  return objectMapper.readValue(inputStream, templateClass);
 }
}

代码示例来源:origin: google/guava

@Override
public byte[] read() throws IOException {
 try (SeekableByteChannel channel = Files.newByteChannel(path, options)) {
  return ByteStreams.toByteArray(Channels.newInputStream(channel), channel.size());
 }
}

代码示例来源:origin: stackoverflow.com

// STEP 1:  Create random access file read-only
RandomAccessFile raf = new RandomAccessFile("/text.txt", "r");

// STEP 2:  Use Channels to convert to InputStream
InputStream is = Channels.newInputStream(raf.getChannel());

代码示例来源:origin: apache/incubator-druid

/**
  * Open a stream to a file.
  *
  * @param offset If zero, stream the entire log. If positive, read from this byte position onwards. If negative,
  *               read this many bytes from the end of the file.
  *
  * @return input supplier for this log, if available from this provider
  */
 public static InputStream streamFile(final File file, final long offset) throws IOException
 {
  final RandomAccessFile raf = new RandomAccessFile(file, "r");
  final long rafLength = raf.length();
  if (offset > 0) {
   raf.seek(offset);
  } else if (offset < 0 && offset < rafLength) {
   raf.seek(Math.max(0, rafLength + offset));
  }
  return Channels.newInputStream(raf.getChannel());
 }
}

代码示例来源:origin: spotify/docker-client

@Override
public InputStream getInputStream() throws IOException {
 if (!channel.isOpen()) {
  throw new SocketException("Socket is closed");
 }
 if (inputShutdown) {
  throw new SocketException("Socket input is shutdown");
 }
 return new FilterInputStream(Channels.newInputStream(channel)) {
  @Override
  public void close() throws IOException {
   shutdownInput();
  }
 };
}

代码示例来源:origin: fabric8io/docker-maven-plugin

@Override
public InputStream getInputStream() throws IOException {
  if (!channel.isOpen()) {
    throw new SocketException("Socket is closed");
  }
  if (inputShutdown) {
    throw new SocketException("Socket input is shutdown");
  }
  return new FilterInputStream(Channels.newInputStream(channel)) {
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
      int readed = super.read(b, off, len);
      log.debug("RESPONSE %s", new String(b, off, len, Charset.forName("UTF-8")));
      return readed;
    }
    @Override
    public void close() throws IOException {
      shutdownInput();
    }
  };
}

代码示例来源:origin: google/j2objc

@Override
public byte[] read() throws IOException {
 try (SeekableByteChannel channel = Files.newByteChannel(path, options)) {
  return ByteStreams.toByteArray(Channels.newInputStream(channel), channel.size());
 }
}

代码示例来源:origin: square/okhttp

BlockingUnixSocket(File path, UnixSocketChannel channel) {
 super(channel);
 this.path = path;
 this.in = Channels.newInputStream(new UnselectableReadableByteChannel());
 this.out = Channels.newOutputStream(new UnselectableWritableByteChannel());
}

代码示例来源:origin: wildfly/wildfly

@Override
public byte[] read() throws IOException {
 try (SeekableByteChannel channel = Files.newByteChannel(path, options)) {
  return ByteStreams.toByteArray(Channels.newInputStream(channel), channel.size());
 }
}

代码示例来源:origin: web3j/web3j

public UnixDomainSocket(String ipcSocketPath, int bufferSize) {
  this.bufferSize = bufferSize;
  try {
    UnixSocketAddress address = new UnixSocketAddress(ipcSocketPath);
    channel = UnixSocketChannel.open(address);
    reader = new InputStreamReader(Channels.newInputStream(channel));
    writer = new PrintWriter(Channels.newOutputStream(channel));
  } catch (IOException e) {
    throw new RuntimeException(
        "Provided file socket cannot be opened: " + ipcSocketPath, e);
  }
}

代码示例来源:origin: prestodb/presto

@Override
public byte[] read() throws IOException {
 try (SeekableByteChannel channel = Files.newByteChannel(path, options)) {
  return com.facebook.presto.jdbc.internal.guava.io.Files.readFile(
    Channels.newInputStream(channel), channel.size());
 }
}

代码示例来源:origin: fabric8io/docker-maven-plugin

@Override
public InputStream getInputStream() throws IOException {
  if (!channel.isOpen()) {
    throw new SocketException("Socket is closed");
  }
  if (!channel.isConnected()) {
    throw new SocketException("Socket is not connected");
  }
  if (inputShutdown) {
    throw new SocketException("Socket input is shutdown");
  }
  return new FilterInputStream(Channels.newInputStream(channel)) {
    @Override
    public void close() throws IOException {
      shutdownInput();
    }
  };
}

代码示例来源:origin: soabase/exhibitor

@Override
public LoadedInstanceConfig loadConfig() throws Exception
{
  File            propertiesFile = new File(propertiesDirectory, propertyFileName);
  Properties      properties = new Properties();
  if ( propertiesFile.exists() )
  {
    RandomAccessFile    raf = new RandomAccessFile(propertiesFile, "rw");
    try
    {
      FileLock        lock = raf.getChannel().lock();
      try
      {
        properties.load(Channels.newInputStream(raf.getChannel()));
      }
      finally
      {
        lock.release();
      }
    }
    finally
    {
      CloseableUtils.closeQuietly(raf);
    }
  }
  PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig(properties, defaults);
  return new LoadedInstanceConfig(config, propertiesFile.lastModified());
}

代码示例来源:origin: sannies/mp4parser

@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
  ByteBuffer byteBuffer = ByteBuffer.allocate(8);
  dataSource.read((ByteBuffer) byteBuffer.rewind());
  byteBuffer.position(6);
  dataReferenceIndex = IsoTypeReader.readUInt16(byteBuffer);
  byte[] namespaceBytes = new byte[0];
  int read;
  while ((read = Channels.newInputStream(dataSource).read()) != 0) {
    namespaceBytes = Mp4Arrays.copyOfAndAppend(namespaceBytes, (byte) read);
  }
  namespace = Utf8.convert(namespaceBytes);
  byte[] schemaLocationBytes = new byte[0];
  while ((read = Channels.newInputStream(dataSource).read()) != 0) {
    schemaLocationBytes = Mp4Arrays.copyOfAndAppend(schemaLocationBytes, (byte) read);
  }
  schemaLocation = Utf8.convert(schemaLocationBytes);
  byte[] auxiliaryMimeTypesBytes = new byte[0];
  while ((read = Channels.newInputStream(dataSource).read()) != 0) {
    auxiliaryMimeTypesBytes = Mp4Arrays.copyOfAndAppend(auxiliaryMimeTypesBytes, (byte) read);
  }
  auxiliaryMimeTypes = Utf8.convert(auxiliaryMimeTypesBytes);
  initContainer(dataSource, contentSize - (header.remaining() + namespace.length() + schemaLocation.length() + auxiliaryMimeTypes.length() + 3), boxParser);
}

代码示例来源:origin: google/data-transfer-project

InputStream getStream(UUID jobId, String keyName) {
 String blobName = getDataKeyName(jobId, keyName);
 Blob blob = bucket.get(blobName);
 ReadChannel channel = blob.reader();
 return Channels.newInputStream(channel);
}

代码示例来源:origin: apache/maven

props.load( Channels.newInputStream( channel ) );

代码示例来源:origin: org.apache.commons/commons-compress

/**
 * Expands {@code archive} into {@code targetDirectory}.
 *
 * @param archive the file to expand
 * @param targetDirectory the directory to write to
 * @param format the archive format. This uses the same format as
 * accepted by {@link ArchiveStreamFactory}.
 * @throws IOException if an I/O error occurs
 * @throws ArchiveException if the archive cannot be read for other reasons
 */
public void expand(String format, SeekableByteChannel archive, File targetDirectory)
  throws IOException, ArchiveException {
  if (!prefersSeekableByteChannel(format)) {
    expand(format, Channels.newInputStream(archive), targetDirectory);
  } else if (ArchiveStreamFactory.ZIP.equalsIgnoreCase(format)) {
    expand(new ZipFile(archive), targetDirectory);
  } else if (ArchiveStreamFactory.SEVEN_Z.equalsIgnoreCase(format)) {
    expand(new SevenZFile(archive), targetDirectory);
  } else {
    // never reached as prefersSeekableByteChannel only returns true for ZIP and 7z
    throw new ArchiveException("don't know how to handle format " + format);
  }
}

代码示例来源:origin: jooby-project/jooby

@SuppressWarnings({"rawtypes", "unchecked" })
@Override
public void render(final Object value, final Context ctx) throws Exception {
 Object model = value;
 /** View? */
 if (value instanceof View) {
  View view = (View) value;
  String path = path(Route.normalize(prefix + "/" + view.name() + suffix));
  Map data = view.model();
  model = Rocker.template(path).bind(data);
 }
 /** RockerModel: */
 if (model instanceof RockerModel) {
  ArrayOfByteArraysOutput output = ((RockerModel) model).render(ArrayOfByteArraysOutput.FACTORY,
    template -> {
     if (template instanceof RequestRockerTemplate) {
      RequestRockerTemplate rrt = (RequestRockerTemplate) template;
      rrt.locals = ctx.locals();
     }
    });
  ctx.type(MediaType.html)
    .length(output.getByteLength())
    // FIXME: make more efficient. Context should provide a way to send partial results
    .send(Channels.newInputStream(output.asReadableByteChannel()));
 }
}

代码示例来源:origin: sannies/mp4parser

public VideoParameterSet(ByteBuffer vps) throws IOException {
  this.vps = vps;
  CAVLCReader r = new CAVLCReader(Channels.newInputStream(new ByteBufferByteChannel((ByteBuffer) vps.position(0))));
  vps_parameter_set_id = r.readU(4, "vps_parameter_set_id");
  int vps_reserved_three_2bits = r.readU(2, "vps_reserved_three_2bits");

相关文章