Example usage for java.io InputStream available

List of usage examples for java.io InputStream available

Introduction

In this page you can find the example usage for java.io InputStream available.

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected.

Usage

From source file:gridool.db.partitioning.phihash.csv.distmm.InMemoryIndexHelper.java

/**
 * Synchronization is required.// w w  w .  j  a v a 2  s .  c  o m
 */
public static void writeToFile(final InputStream in) throws IOException {
    final byte[] recordBuf = new byte[2048]; // big buffer enough for a record
    final Map<String, OutputStream> outputMap = new HashMap<String, OutputStream>(12);
    while (in.available() > 0) {
        String fkIdxName = IOUtils.readString(in);
        int bucket = IOUtils.readInt(in);
        int recordlen = IOUtils.readInt(in);
        IOUtils.readFully(in, recordBuf, 0, recordlen);

        OutputStream out = prepareFkOutputStream(fkIdxName, bucket, outputMap);
        out.write(recordBuf, 0, recordlen);
    }
    for (OutputStream out : outputMap.values()) {
        out.flush();
        out.close();
    }
}

From source file:Main.java

private static byte[] getBytesFromDriveVideoUri(Context context, Uri uri) {
    InputStream inputStream = null;
    try {//from  w w  w  .j  a va 2s.co m
        inputStream = context.getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    if (inputStream == null) {
        return null;
    }

    int maxBufferSize = 1024 * 1024;
    int available = 0;
    try {
        available = inputStream.available();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (available == 0) {
        available = maxBufferSize;
    }

    int bufferSize = Math.min(available, maxBufferSize);

    byte[] data = new byte[bufferSize];
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;

    try {
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        buffer.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return buffer.toByteArray();
}

From source file:Main.java

public static int readInputStream(InputStream input, byte[] buffer, int offset, int length) throws Exception {
    int n, o;/*w ww .ja  va 2s.c om*/

    if (buffer == null)
        throw new NullPointerException();
    if (offset < 0 || length < 0 || offset + length > buffer.length)
        throw new IndexOutOfBoundsException();
    if (length == 0)
        return 0;

    if ((n = input.read(buffer, offset++, 1)) < 0)
        return -1;

    if (--length > 0 && (o = input.available()) > 0) {
        n += input.read(buffer, offset, o > length ? length : o);
    }

    return n;
}

From source file:com.spoiledmilk.ibikecph.util.Util.java

public static String stringFromJsonAssets(Context context, String path) {
    String bufferString = "";
    try {//from  www  .j  a v a 2  s.  c om
        InputStream is = context.getAssets().open(path);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        bufferString = new String(buffer);
    } catch (Exception e) {
        LOG.e(e.getLocalizedMessage());
    }
    return bufferString;
}

From source file:com.openatlas.android.initializer.BundleParser.java

public static void parser(Context mContext) {
    InputStream is;
    ArrayList<BundleInfoList.BundleInfo> bundleInfos = new ArrayList<BundleInfoList.BundleInfo>();
    ArrayList<BundleListing.Component> mComponents = new ArrayList<BundleListing.Component>();

    try {// w  ww .  j ava 2 s.  co  m
        is = mContext.getAssets().open("bundle-info.json");
        int size = is.available();

        // Read the entire asset into a local byte buffer.  
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        JSONArray jsonArray = new JSONArray(new String(buffer));
        for (int index = 0; index < jsonArray.length(); index++) {
            JSONObject tmp = jsonArray.optJSONObject(index);
            BundleInfo mBundleInfo = new BundleInfo();
            BundleListing.Component mComponent = new BundleListing.Component();
            mBundleInfo.bundleName = tmp.optString("pkgName");
            mBundleInfo.hasSO = tmp.optBoolean("hasSO");
            mComponent.setPkgName(mBundleInfo.bundleName);
            mComponent.setHasSO(mBundleInfo.hasSO);
            ArrayList<String> components = new ArrayList<String>();

            JSONArray activities = tmp.optJSONArray("activities");
            for (int j = 0; j < activities.length(); j++) {
                components.add(activities.getString(j));
                mComponent.getActivities().add(activities.getString(j));
            }

            JSONArray receivers = tmp.optJSONArray("receivers");
            for (int j = 0; j < receivers.length(); j++) {
                components.add(receivers.getString(j));
                mComponent.getReceivers().add(receivers.getString(j));
            }

            JSONArray services = tmp.optJSONArray("services");
            for (int j = 0; j < services.length(); j++) {
                components.add(services.getString(j));
                mComponent.getServices().add(services.getString(j));
            }

            JSONArray contentProviders = tmp.optJSONArray("contentProviders");
            for (int j = 0; j < contentProviders.length(); j++) {
                components.add(contentProviders.getString(j));
                mComponent.getContentProviders().add(contentProviders.getString(j));

            }

            JSONArray dependencys = tmp.optJSONArray("dependency");
            for (int j = 0; j < dependencys.length(); j++) {
                mBundleInfo.DependentBundles.add(dependencys.getString(j));
                mComponent.getDependency().add(dependencys.getString(j));

            }
            mBundleInfo.Components = components;
            bundleInfos.add(mBundleInfo);
            mComponents.add(mComponent);
            BundleInfoList.getInstance().init(bundleInfos);
        }
        BundleListing.getInstance().setBundles(mComponents);
        //BundleInfoList.getInstance().init(bundleInfos);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:mobisocial.musubi.objects.FileObj.java

public static Obj from(Context context, Uri dataUri) throws IOException {
    //TODO: is this the proper way to do it?
    if (dataUri == null) {
        throw new NullPointerException();
    }/*from  w  ww  .  j av  a2  s  .  c  om*/
    ContentResolver cr = context.getContentResolver();
    InputStream in = cr.openInputStream(dataUri);
    long length = in.available();

    String ext;
    String mimeType;
    String filename;

    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    if ("content".equals(dataUri.getScheme())) {
        ContentResolver resolver = context.getContentResolver();
        mimeType = resolver.getType(dataUri);
        ext = mimeTypeMap.getExtensionFromMimeType(mimeType);
        filename = "Musubi-" + sDateFormat.format(new Date());
    } else {
        ext = MimeTypeMap.getFileExtensionFromUrl(dataUri.toString());
        mimeType = mimeTypeMap.getMimeTypeFromExtension(ext);
        filename = Uri.parse(dataUri.toString()).getLastPathSegment();
        if (filename == null) {
            filename = "Musubi-" + sDateFormat.format(new Date());
        }
    }

    if (mimeType == null || mimeType.isEmpty()) {
        throw new IOException("Unidentified mime type");
    }

    if (ext == null || ext.isEmpty()) {
        ext = mimeTypeMap.getExtensionFromMimeType(mimeType);
    }

    if (!ext.isEmpty() && !filename.endsWith(ext)) {
        filename = filename + "." + ext;
    }

    if (mimeType.startsWith("video/")) {
        return VideoObj.from(context, dataUri, mimeType);
    } else if (mimeType.startsWith("image/")) {
        return PictureObj.from(context, dataUri, true);
    }

    if (length > EMBED_SIZE_LIMIT) {
        if (length > CORRAL_SIZE_LIMIT) {
            throw new IOException("file too large for push");
        } else {
            return fromCorral(context, mimeType, filename, length, dataUri);
        }
    } else {
        in = cr.openInputStream(dataUri);
        return from(mimeType, filename, length, IOUtils.toByteArray(in));
    }
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

protected static String executeSSHRemoteCommand(String host, String command, String user, String password)
        throws OpenTSDBException {
    JSch jsch = new JSch();

    StringBuilder sb = new StringBuilder();

    try {/* w w  w. j av a  2 s.  c o m*/
        Session session = jsch.getSession(user, host, 22);

        //username and password will be given via UserInfo interface.
        UserInfo ui = new MyUserInfo(password);
        session.setUserInfo(ui);
        session.connect();

        Channel channel = session.openChannel("exec");

        ((ChannelExec) channel).setCommand(command);

        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        InputStream in = channel.getInputStream();

        channel.connect();

        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                sb.append(new String(tmp, 0, i));
            }

            if (channel.isClosed()) {
                if (in.available() > 0)
                    continue;
                sb.append("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();

    } catch (JSchException e) {
        throw new OpenTSDBException("Unable to connect to OpenTSDB host.", e);
    } catch (IOException e) {
        throw new OpenTSDBException("Unable to connect to OpenTSDB host.", e);
    }

    return sb.toString();
}

From source file:com.google.zxing.web.DecodeServlet.java

private static void consumeRemainder(InputStream is) {
    try {//from www.j  a  v  a  2 s  .  co  m
        int available;
        while ((available = is.available()) > 0) {
            is.read(REMAINDER_BUFFER, 0, available); // don't care about value, or collision
        }
    } catch (IOException | IndexOutOfBoundsException ioe) {
        // sun.net.www.http.ChunkedInputStream.read is throwing IndexOutOfBoundsException
        // continue
    }
}

From source file:com.aegiswallet.utils.BasicUtils.java

public static JSONObject parseJSONData(Context context, String fileName) {
    String JSONString = null;/*ww  w . j  a  v  a 2 s. c  o  m*/
    JSONObject JSONObject = null;
    try {

        //open the inputStream to the file
        InputStream inputStream = context.openFileInput(fileName);

        int sizeOfJSONFile = inputStream.available();

        //array that will store all the data
        byte[] bytes = new byte[sizeOfJSONFile];

        //reading data into the array from the file
        inputStream.read(bytes);

        //close the input stream
        inputStream.close();

        JSONString = new String(bytes, "UTF-8");
        JSONObject = new JSONObject(JSONString);

    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    } catch (JSONException x) {
        return null;
    }
    return JSONObject;
}

From source file:gridool.communication.transport.tcp.GridMasterSlaveWorkerServer.java

static boolean handleConnection(final Socket clientSocket, final GridTransportListener listener,
        final ExecutorService msgProcPool) {
    final InputStream is;
    final int size;
    try {/*from www.  jav  a 2  s  .  c  o m*/
        is = clientSocket.getInputStream();
        if (LOG.isDebugEnabled()) {
            final int available = is.available();
            if (available == 0) {
                LOG.debug("Reading data from socket [" + clientSocket + "] seems to be blocked");
            }
        }
        size = IOUtils.readUnsignedIntOrEOF(is);
    } catch (IOException e) {
        LOG.fatal(PrintUtils.prettyPrintStackTrace(e, -1));
        return false;
    }
    if (size == -1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Connection is closed by remote peer: " + clientSocket);
        }
        return false;
    } else if (size <= 0) {
        LOG.warn("Illegal message (size: " + size + ") was detected for a connection: " + clientSocket);
        return false;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Start reading " + size + " bytes from a socket [" + clientSocket + ']');
    }
    // read an object from stream
    final byte[] b = new byte[size];
    try {
        IOUtils.readFully(is, b, 0, size);
    } catch (IOException ioe) {
        LOG.fatal("Failed to read data from " + clientSocket, ioe);
        return false;
    }
    msgProcPool.execute(new Runnable() {
        public void run() {
            processRequest(b, listener, clientSocket);
        }
    });
    return true;
}