Tabnine Logo
InputStream.available
Code IndexAdd Tabnine to your IDE (free)

How to use
available
method
in
java.io.InputStream

Best Java code snippets using java.io.InputStream.available (Showing top 20 results out of 20,367)

Refine searchRefine arrow

  • InputStream.read
  • InputStream.close
  • PrintStream.println
  • OutputStream.write
  • IOException.<init>
  • File.<init>
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) {
  }
}
java.ioInputStreamavailable

Javadoc

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.

Popular methods of InputStream

  • close
    Closes this input stream and releases any system resources associated with the stream. The close met
  • read
    Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to re
  • skip
    Skips over and discards n bytes of data from this input stream. The skip method may, for a variety o
  • reset
    Repositions this stream to the position at the time themark method was last called on this input str
  • mark
    Marks the current position in this input stream. A subsequent call to the reset method repositions
  • markSupported
    Tests if this input stream supports the mark andreset methods. Whether or not mark andreset are sup
  • transferTo
  • <init>
    This constructor does nothing. It is provided for signature compatibility.
  • readAllBytes
  • readNBytes

Popular in Java

  • Running tasks concurrently on multiple threads
  • scheduleAtFixedRate (ScheduledExecutorService)
  • getSystemService (Context)
  • setRequestProperty (URLConnection)
  • LinkedList (java.util)
    Doubly-linked list implementation of the List and Dequeinterfaces. Implements all optional list oper
  • List (java.util)
    An ordered collection (also known as a sequence). The user of this interface has precise control ove
  • Locale (java.util)
    Locale represents a language/country/variant combination. Locales are used to alter the presentatio
  • Set (java.util)
    A Set is a data structure which does not allow duplicate elements.
  • StringTokenizer (java.util)
    Breaks a string into tokens; new code should probably use String#split.> // Legacy code: StringTo
  • Servlet (javax.servlet)
    Defines methods that all servlets must implement. A servlet is a small Java program that runs within
  • Top PhpStorm plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now