okio.Source类的使用及代码示例

x33g5p2x  于2022-01-30 转载在 其他  
字(10.0k)|赞(0)|评价(0)|浏览(264)

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

Source介绍

[英]Supplies a stream of bytes. Use this interface to read data from wherever it's located: from the network, storage, or a buffer in memory. Sources may be layered to transform supplied data, such as to decompress, decrypt, or remove protocol framing.

Most applications shouldn't operate on a source directly, but rather on a BufferedSource which is both more efficient and more convenient. Use Okio#buffer(Source) to wrap any source with a buffer.

Sources are easy to test: just use a Buffer in your tests, and fill it with the data your application is to read.

Comparison with InputStream

This interface is functionally equivalent to java.io.InputStream.

InputStream requires multiple layers when consumed data is heterogeneous: a DataInputStream for primitive values, a BufferedInputStream for buffering, and InputStreamReader for strings. This class uses BufferedSource for all of the above.

Source avoids the impossible-to-implement java.io.InputStream#available method. Instead callers specify how many bytes they BufferedSource#require.

Source omits the unsafe-to-compose java.io.InputStream#mark state that's tracked by InputStream; instead, callers just buffer what they need.

When implementing a source, you don't need to worry about the java.io.InputStream#read method that is awkward to implement efficiently and returns one of 257 possible values.

And source has a stronger skip method: BufferedSource#skipwon't return prematurely.

Interop with InputStream

Use Okio#source to adapt an InputStream to a source. Use BufferedSource#inputStream to adapt a source to an InputStream.
[中]提供字节流。使用此接口从任何位置读取数据:从网络、存储器或内存中的缓冲区。源可以分层以转换提供的数据,例如解压缩、解密或移除协议帧。
大多数应用程序不应该直接在源上运行,而应该在更高效、更方便的缓冲源上运行。使用Okio#buffer(Source)将任何源包装成一个缓冲区。
源代码很容易测试:只需在测试中使用缓冲区,并用应用程序要读取的数据填充它。
####与InputStream的比较
这个接口在功能上等同于java。伊奥。输入流。
当使用的数据是异构数据时,InputStream需要多个层:用于基本值的DataInputStream、用于缓冲的BufferedInputStream和用于字符串的InputStreamReader。该类使用BufferedSource实现上述所有功能。
源代码避免了实现java的不可能。伊奥。InputStream#可用方法。相反,调用者指定缓冲源所需的字节数。
Source省略了编写java的不安全代码。伊奥。InputStream#标记InputStream跟踪的状态;相反,呼叫者只是缓冲他们需要的东西。
在实现源代码时,您不需要担心java。伊奥。InputStream#read方法,难以有效实现,返回257个可能值中的一个。
source有一个更强的跳过方法:BufferedSource#skipwon不会过早返回。
####与InputStream互操作
使用Okio#source使输入流适应源。使用BufferedSource#inputStream使源适应inputStream。

代码示例

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

@Test public void testReadChannel() throws Exception {
 ReadableByteChannel channel = new Buffer().writeUtf8(quote);
 Buffer buffer = new Buffer();
 Source source = new ByteChannelSource(channel, Timeout.NONE);
 source.read(buffer, 75);
 assertThat(buffer.readUtf8())
   .isEqualTo("John, the kind of control you're attempting simply is... it's not possible.");
}

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

@Override public ByteString call() throws Exception {
  Buffer blackhole = new Buffer();
  HashingSink hashingSink = HashingSink.sha1(blackhole);
  Buffer buffer = new Buffer();
  while (pipe.source().read(buffer, Long.MAX_VALUE) != -1) {
   hashingSink.write(buffer, buffer.size());
   blackhole.clear();
  }
  pipe.source().close();
  return hashingSink.hash();
 }
});

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

/**
 * Reads until {@code in} is exhausted or the deadline has been reached. This is careful to not
 * extend the deadline if one exists already.
 */
public static boolean skipAll(Source source, int duration, TimeUnit timeUnit) throws IOException {
 long now = System.nanoTime();
 long originalDuration = source.timeout().hasDeadline()
   ? source.timeout().deadlineNanoTime() - now
   : Long.MAX_VALUE;
 source.timeout().deadlineNanoTime(now + Math.min(originalDuration, timeUnit.toNanos(duration)));
 try {
  Buffer skipBuffer = new Buffer();
  while (source.read(skipBuffer, 8192) != -1) {
   skipBuffer.clear();
  }
  return true; // Success! The source has been exhausted.
 } catch (InterruptedIOException e) {
  return false; // We ran out of time before exhausting the source.
 } finally {
  if (originalDuration == Long.MAX_VALUE) {
   source.timeout().clearDeadline();
  } else {
   source.timeout().deadlineNanoTime(now + originalDuration);
  }
 }
}

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

/** Reads all bytes from {@code source} and writes them to {@code sink}. */
private Long readAllAndClose(Source source, Sink sink) throws IOException {
 long result = 0L;
 Buffer buffer = new Buffer();
 for (long count; (count = source.read(buffer, SEGMENT_SIZE)) != -1L; result += count) {
  sink.write(buffer, count);
 }
 source.close();
 sink.close();
 return result;
}

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

@Override public void writeTo(BufferedSink sink) throws IOException {
  Buffer buffer = new Buffer();
  while (pipe.source().read(buffer, 8192) != -1L) {
   sink.write(buffer, buffer.size());
  }
 }
}

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

@Override public void run() {
  try {
   Buffer buffer = new Buffer();
   Thread.sleep(1000L);
   assertEquals(3, pipe.source().read(buffer, Long.MAX_VALUE));
   assertEquals("abc", buffer.readUtf8());
   Thread.sleep(1000L);
   assertEquals(3, pipe.source().read(buffer, Long.MAX_VALUE));
   assertEquals("def", buffer.readUtf8());
   Thread.sleep(1000L);
   assertEquals(3, pipe.source().read(buffer, Long.MAX_VALUE));
   assertEquals("ghi", buffer.readUtf8());
   Thread.sleep(1000L);
   assertEquals(3, pipe.source().read(buffer, Long.MAX_VALUE));
   assertEquals("jkl", buffer.readUtf8());
  } catch (IOException | InterruptedException e) {
   throw new AssertionError();
  }
 }
});

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

/**
 * Read data from {@code source} and write it to {@code sink}. This doesn't use {@link
 * BufferedSink#writeAll} because that method doesn't flush aggressively and we need that.
 */
private void transfer(Socket sourceSocket, Source source, Sink sink) {
 try {
  Buffer buffer = new Buffer();
  for (long byteCount; (byteCount = source.read(buffer, 8192L)) != -1; ) {
   sink.write(buffer, byteCount);
   sink.flush();
  }
 } catch (IOException e) {
  System.out.println("transfer failed from " + sourceSocket + ": " + e);
 } finally {
  closeQuietly(sink);
  closeQuietly(source);
  closeQuietly(sourceSocket);
  openSockets.remove(sourceSocket);
 }
}

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

System.out.println("Cipher   : " + cipher);
Buffer wire = new Buffer();
Buffer transmit = new Buffer();
transmit.writeUtf8("This is not really a secure message");
System.out.println("Transmit : " + transmit);
Buffer receive = new Buffer();
source.read(receive, Long.MAX_VALUE);
System.out.println("Receive  : " + receive);

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

long bufferPos = upstreamPos - buffer.size();
buffer.copyTo(sink, sourcePos - bufferPos, bytesToRead);
sourcePos += bytesToRead;
return bytesToRead;
long upstreamBytesRead = upstream.read(upstreamBuffer, bufferMaxSize);
upstreamBuffer.copyTo(sink, 0, bytesRead);
sourcePos += bytesRead;

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

@Test public void sinkCloseFailsIfReaderIsClosedBeforeAllDataIsRead() throws Exception {
 Pipe pipe = new Pipe(100L);
 pipe.sink().write(new Buffer().writeUtf8("abc"), 3);
 pipe.source().close();
 try {
  pipe.sink().close();
  fail();
 } catch (IOException expected) {
  assertEquals("source is closed", expected.getMessage());
 }
}

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

@Test public void sourceTimeout() throws Exception {
 Pipe pipe = new Pipe(3L);
 pipe.source().timeout().timeout(1000, TimeUnit.MILLISECONDS);
 double start = now();
 Buffer readBuffer = new Buffer();
 try {
  pipe.source().read(readBuffer, 6L);
  fail();
 } catch (InterruptedIOException expected) {
  assertEquals("timeout", expected.getMessage());
 }
 assertElapsed(1000.0, start);
 assertEquals(0, readBuffer.size());
}

代码示例来源:origin: liferay/liferay-mobile-sdk

public static void transfer(
    InputStream is, FileProgressCallback callback, Object tag,
    BufferedSink sink)
  throws IOException {
  Source source = null;
  try {
    source = Okio.source(is);
    Buffer os = new Buffer();
    while ((source.read(os, 2048) != -1) && !isCancelled(callback)) {
      byte[] bytes = os.readByteArray();
      if (sink != null) {
        sink.write(bytes);
      }
      if (callback != null) {
        callback.onBytes(bytes);
        callback.increment(bytes.length);
      }
    }
    if (isCancelled(callback)) {
      HttpUtil.cancel(tag);
    }
  }
  finally {
    Util.closeQuietly(source);
  }
}

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

@Test public void wrappedSourceCloseTimesOut() throws Exception {
 Source source = new ForwardingSource(new Buffer()) {
  @Override public void close() throws IOException {
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    throw new AssertionError();
   }
  }
 };
 AsyncTimeout timeout = new AsyncTimeout();
 timeout.timeout(250, TimeUnit.MILLISECONDS);
 Source timeoutSource = timeout.source(source);
 try {
  timeoutSource.close();
  fail();
 } catch (InterruptedIOException expected) {
 }
}

代码示例来源:origin: rengwuxian/HenCoderPlus

private static void okio1() {
  try (Source source = Okio.buffer(Okio.source(new File("./19_io/text.txt")))) {
    Buffer buffer = new Buffer();
    source.read(buffer, 1024);
    System.out.println(buffer.readUtf8Line());
    System.out.println(buffer.readUtf8Line());
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

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

body.close();
  if (!source.getBuffer().exhausted() || !sink.buffer().exhausted()) {
   throw new IOException("TLS tunnel buffered too many bytes!");

代码示例来源:origin: apollographql/apollo-android

@Override public long read(Buffer sink, long byteCount) throws IOException {
 long bytesRead;
 try {
  bytesRead = responseBodySource.read(sink, byteCount);
 } catch (IOException e) {
  if (!closed) {
   // Failed to write a complete cache response.
   closed = true;
   abortCacheQuietly();
  }
  throw e;
 }
 if (bytesRead == -1) {
  if (!closed) {
   // The cache response is complete!
   closed = true;
   commitCache();
  }
  return -1;
 }
 responseBodyCacheSink.copyFrom(sink, sink.size() - bytesRead, bytesRead);
 return bytesRead;
}

代码示例来源:origin: huxq17/tractor

@Override public void skip(long byteCount) throws IOException {
 if (closed) throw new IllegalStateException("closed");
 while (byteCount > 0) {
  if (buffer.size == 0 && source.read(buffer, Segment.SIZE) == -1) {
   throw new EOFException();
  }
  long toSkip = Math.min(byteCount, buffer.size());
  buffer.skip(toSkip);
  byteCount -= toSkip;
 }
}

代码示例来源:origin: huxq17/tractor

@Override public long readAll(Sink sink) throws IOException {
 if (sink == null) throw new IllegalArgumentException("sink == null");
 long totalBytesWritten = 0;
 while (source.read(buffer, Segment.SIZE) != -1) {
  long emitByteCount = buffer.completeSegmentByteCount();
  if (emitByteCount > 0) {
   totalBytesWritten += emitByteCount;
   sink.write(buffer, emitByteCount);
  }
 }
 if (buffer.size() > 0) {
  totalBytesWritten += buffer.size();
  sink.write(buffer, buffer.size());
 }
 return totalBytesWritten;
}

代码示例来源:origin: apollographql/apollo-android

static void closeQuietly(Source source) {
 try {
  source.close();
 } catch (Exception ignore) {
  // ignore
 }
}

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

@Override public long read(Buffer sink, long byteCount) throws IOException {
 long result = source.read(sink, byteCount);
 if (result == -1) exhausted = true;
 return result;
}

相关文章