java.io.InputStream.available()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(11.5k)|赞(0)|评价(0)|浏览(312)

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

InputStream.available介绍

[英]Returns an estimated number of bytes that can be read or skipped without blocking for more input.

Note that this method provides such a weak guarantee that it is not very useful in practice.

Firstly, the guarantee is "without blocking for more input" rather than "without blocking": a read may still block waiting for I/O to complete — the guarantee is merely that it won't have to wait indefinitely for data to be written. The result of this method should not be used as a license to do I/O on a thread that shouldn't be blocked.

Secondly, the result is a conservative estimate and may be significantly smaller than the actual number of bytes available. In particular, an implementation that always returns 0 would be correct. In general, callers should only use this method if they'd be satisfied with treating the result as a boolean yes or no answer to the question "is there definitely data ready?".

Thirdly, the fact that a given number of bytes is "available" does not guarantee that a read or skip will actually read or skip that many bytes: they may read or skip fewer.

It is particularly important to realize that you must not use this method to size a container and assume that you can read the entirety of the stream without needing to resize the container. Such callers should probably write everything they read to a ByteArrayOutputStream and convert that to a byte array. Alternatively, if you're reading from a file, File#length returns the current length of the file (though assuming the file's length can't change may be incorrect, reading a file is inherently racy).

The default implementation of this method in InputStream always returns 0. Subclasses should override this method if they are able to indicate the number of bytes available.
[中]返回在不阻止更多输入的情况下可以读取或跳过的估计字节数。
请注意,此方法提供的保证很弱,因此在实践中不是很有用。
首先,保证是“不阻塞更多输入”,而不是“不阻塞”:读操作可能仍然阻塞等待I/O完成-保证只是不必无限期地等待数据写入。此方法的结果不应用作在不应被阻止的线程上执行I/O的许可证。
其次,结果是保守估计,可能比实际可用字节数小得多。特别是,始终返回0的实现是正确的。通常,调用者只有在满足于将结果视为“是否确实有数据准备就绪?”问题的布尔“是”或“否”答案时才应使用此方法。
第三,给定数量的字节是“可用”的这一事实并不保证读取或跳过的字节数会达到这么多:它们读取或跳过的字节数可能会更少。
特别重要的是要认识到,您不能使用此方法来调整容器的大小,并假设您可以读取整个流,而无需调整容器的大小。此类调用者可能应该将读取的所有内容写入ByteArrayOutputStream,并将其转换为字节数组。或者,如果您正在读取文件,file#length将返回文件的当前长度(尽管假设文件长度不能更改可能是不正确的,读取文件本身就是一种快速行为)。
InputStream中此方法的默认实现始终返回0。如果子类能够指示可用的字节数,则应重写此方法。

代码示例

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

private byte[] readMessageData(InputStream is) throws IOException {
  if (is.available() > 0) {
    byte[] result = new byte[is.available()];
    is.read(result);
    return result;
  }
  return new byte[]{};
}

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

/**
 * write.
 *
 * @param is         InputStream instance.
 * @param os         OutputStream instance.
 * @param bufferSize buffer size.
 * @return count.
 * @throws IOException
 */
public static long write(InputStream is, OutputStream os, int bufferSize) throws IOException {
  int read;
  long total = 0;
  byte[] buff = new byte[bufferSize];
  while (is.available() > 0) {
    read = is.read(buff, 0, buff.length);
    if (read > 0) {
      os.write(buff, 0, read);
      total += read;
    }
  }
  return total;
}

代码示例来源:origin: pxb1988/dex2jar

public static byte[] readFile(File in) throws IOException {
  InputStream is = new FileInputStream(in);
  byte[] xml = new byte[is.available()];
  is.read(xml);
  is.close();
  return xml;
}

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

File f = new File(getCacheDir()+"/m1.map");
if (!f.exists()) try {
 InputStream is = getAssets().open("m1.map");
 int size = is.available();
 byte[] buffer = new byte[size];
 is.read(buffer);
 is.close();
 FileOutputStream fos = new FileOutputStream(f);
 fos.write(buffer);
 fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
mapView.setMapFile(f.getPath());

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

public static int keyPress(String msg) {
  System.out.println(msg);
  try {
    int ret=System.in.read();
    System.in.skip(System.in.available());
    return ret;
  }
  catch(IOException e) {
    return -1;
  }
}

代码示例来源:origin: skylot/jadx

private void process(OutputStream out) throws IOException {
  if (template.available() == 0) {
    throw new IOException("Template already processed");
  }
  try (InputStream in = new BufferedInputStream(template)) {
    ParserState state = new ParserState();
    while (true) {
      int ch = in.read();
      if (ch == -1) {
        break;
      }
      String str = process(state, (char) ch);
      if (str != null) {
        out.write(str.getBytes());
      } else if (!state.skip) {
        out.write(ch);
      }
    }
  }
}

代码示例来源:origin: alibaba/canal

public static String loadConfig(String name) {
    // 先取本地文件,再取类路径
    File filePath = new File(".." + File.separator + Constant.CONF_DIR + File.separator + name);
    if (!filePath.exists()) {
      URL url = MappingConfigsLoader.class.getClassLoader().getResource("");
      if (url != null) {
        filePath = new File(url.getPath() + name);
      }
    }
    if (filePath.exists()) {
      String fileName = filePath.getName();
      if (!fileName.endsWith(".yml")) {
        return null;
      }
      try (InputStream in = new FileInputStream(filePath)) {
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        return new String(bytes, StandardCharsets.UTF_8);
      } catch (IOException e) {
        throw new RuntimeException("Read mapping config: " + filePath.getAbsolutePath() + " error. ", e);
      }
    }
    return null;
  }
}

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

/**
 * Reads all available bytes from InputStream as a byte array.
 * Uses <code>in.available()</code> to determine the size of input stream.
 * This is the fastest method for reading input stream to byte array, but
 * depends on stream implementation of <code>available()</code>.
 * Buffered internally.
 */
public static byte[] readAvailableBytes(InputStream in) throws IOException {
  int l = in.available();
  byte[] byteArray = new byte[l];
  int i = 0, j;
  while ((i < l) && (j = in.read(byteArray, i, l - i)) >= 0) {
    i +=j;
  }
  if (i < l) {
    throw new IOException("Failed to completely read input stream");
  }
  return byteArray;
}

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

void printView() {
  System.out.println("\n-- view: " + channel.getView() + '\n');
  try {
    System.in.skip(System.in.available());
  }
  catch(Exception e) {
  }
}

代码示例来源:origin: nutzam/nutz

throws IOException {
if (is == null) {
  throw new IOException("Class not found");
  byte[] b = new byte[is.available()];
  int len = 0;
  while (true) {
    int n = is.read(b, len, b.length - len);
    if (n == -1) {
      if (len < b.length) {
      int last = is.read();
      if (last < 0) {
        return b;
    is.close();

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

/** Returns the length in bytes of this file, or 0 if this file is a directory, does not exist, or the size cannot otherwise be
 * determined. */
public long length () {
  if (type == FileType.Classpath || !file.exists()) {
    InputStream input = read();
    try {
      return input.available();
    } catch (Exception ignored) {
    } finally {
      try {
        input.close();
      } catch (IOException ignored) {
      }
    }
    return 0;
  }
  return file().length();
}

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

@Override
public int available() throws IOException {
  if (buf == null) {
    throw new IOException();
  }
  return buf.length - pos + in.available();
}

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

/** Compresses the given {@link InputStream} into the given {@link OutputStream}.
 * 
 * @param in the {@link InputStream} to compress
 * @param out the {@link OutputStream} to compress to
 * @throws IOException */
static public void compress (InputStream in, OutputStream out) throws IOException {
  CommandLine params = new CommandLine();
  boolean eos = false;
  if (params.Eos) eos = true;
  com.badlogic.gdx.utils.compression.lzma.Encoder encoder = new com.badlogic.gdx.utils.compression.lzma.Encoder();
  if (!encoder.SetAlgorithm(params.Algorithm)) throw new RuntimeException("Incorrect compression mode");
  if (!encoder.SetDictionarySize(params.DictionarySize)) throw new RuntimeException("Incorrect dictionary size");
  if (!encoder.SetNumFastBytes(params.Fb)) throw new RuntimeException("Incorrect -fb value");
  if (!encoder.SetMatchFinder(params.MatchFinder)) throw new RuntimeException("Incorrect -mf value");
  if (!encoder.SetLcLpPb(params.Lc, params.Lp, params.Pb)) throw new RuntimeException("Incorrect -lc or -lp or -pb value");
  encoder.SetEndMarkerMode(eos);
  encoder.WriteCoderProperties(out);
  long fileSize;
  if (eos) {
    fileSize = -1;
  } else {
    if ((fileSize = in.available()) == 0) {
      fileSize = -1;
    }
  }
  for (int i = 0; i < 8; i++) {
    out.write((int)(fileSize >>> (8 * i)) & 0xFF);
  }
  encoder.Code(in, out, -1, -1, null);
}

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

java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
java.util.Enumeration enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
  java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
  java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
  if (file.isDirectory()) { // if its a directory, create it
    f.mkdir();
    continue;
  }
  java.io.InputStream is = jar.getInputStream(file); // get the input stream
  java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
  while (is.available() > 0) {  // write contents of 'is' to 'fos'
    fos.write(is.read());
  }
  fos.close();
  is.close();
}

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

public class Exec
{
  public static void main(String []args) throws Exception
  {
    Process ps=Runtime.getRuntime().exec(new String[]{"java","-jar","A.jar"});
    ps.waitFor();
    java.io.InputStream is=ps.getInputStream();
    byte b[]=new byte[is.available()];
    is.read(b,0,b.length);
    System.out.println(new String(b));
  }
}

代码示例来源:origin: rackerlabs/blueflood

Payload payload = blob.getPayload();
InputStream is = payload.getInput();
File tempFile = new File(downloadDir, name + ".tmp");
Timer.Context downloadContext = downloadTimer.time();
try {
  byte[] buf = new byte[BUF_SIZE];
  while (read < length) {
    int avail = Math.min(is.available(), BUF_SIZE);
    if (avail < 0) {
      try { Thread.sleep(100); } catch (Exception ex) {}
    } else {
      int readLength = is.read(buf);
      read += readLength;
      out.write(buf, 0, readLength);
  File permFile = new File(downloadDir, name);
  if (tempFile.renameTo(permFile)) {
    notifyListeners(permFile);
  } else {
    throw new IOException("Could not rename file");

代码示例来源:origin: alibaba/canal

public static Map<String, String> loadConfigs(String name) {
  Map<String, String> configContentMap = new HashMap<>();
  // 先取本地文件,再取类路径
  File configDir = new File(".." + File.separator + Constant.CONF_DIR + File.separator + name);
  if (!configDir.exists()) {
    URL url = MappingConfigsLoader.class.getClassLoader().getResource("");
    if (url != null) {
      configDir = new File(url.getPath() + name + File.separator);
    }
  }
  File[] files = configDir.listFiles();
  if (files != null) {
    for (File file : files) {
      String fileName = file.getName();
      if (!fileName.endsWith(".yml")) {
        continue;
      }
      try (InputStream in = new FileInputStream(file)) {
        byte[] bytes = new byte[in.available()];
        in.read(bytes);
        String configContent = new String(bytes, StandardCharsets.UTF_8);
        configContentMap.put(fileName, configContent);
      } catch (IOException e) {
        throw new RuntimeException("Read " + name + "mapping config: " + fileName + " error. ", e);
      }
    }
  }
  return configContentMap;
}

代码示例来源:origin: hankcs/HanLP

public static String readTxt(String file, String charsetName) throws IOException
{
  InputStream is = IOAdapter.open(file);
  byte[] targetArray = new byte[is.available()];
  int len;
  int off = 0;
  while ((len = is.read(targetArray, off, targetArray.length - off)) != -1 && off < targetArray.length)
  {
    off += len;
  }
  is.close();
  return new String(targetArray, charsetName);
}

代码示例来源:origin: oblac/jodd

/**
 * Reads all available bytes from {@link InputStream} as a byte array.
 * Uses {@link InputStream#available()} to determine the size of input stream.
 * This is the fastest method for reading {@link InputStream} to byte array, but
 * depends on {@link InputStream} implementation of {@link InputStream#available()}.
 *
 * @param input {@link InputStream} to read.
 * @return byte[]
 * @throws IOException if total read is less than {@link InputStream#available()};
 */
public static byte[] readAvailableBytes(final InputStream input) throws IOException {
  int numToRead = input.available();
  byte[] buffer = new byte[numToRead];
  int totalRead = ZERO;
  int read;
  while ((totalRead < numToRead) && (read = input.read(buffer, totalRead, numToRead - totalRead)) >= ZERO) {
    totalRead = totalRead + read;
  }
  if (totalRead < numToRead) {
    throw new IOException("Failed to completely read InputStream");
  }
  return buffer;
}

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

void printView() {
  System.out.println("\n-- view: " + channel.getView() + '\n');
  try {
    System.in.skip(System.in.available());
  }
  catch(Exception e) {
  }
}

相关文章