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:com.us.util.FileHelper.java

/**
 * ?InputStream//from  w  ww  . j  a va2  s .c  om
 * 
 * @param stream ?
 * 
 *            <pre>
 * 680M: 17610ms
 * 283M: 6245ms
 * 
 * </pre>
 * @return
 * @throws Exception
 */
public static long readLength(InputStream stream) {
    try {
        return stream.available();
    } catch (IOException e) {
        return 0;
    }
}

From source file:com.hangum.tadpole.engine.manager.internal.map.SQLMap.java

/**
 * SQLMap XML to string//from ww  w .  j a  v  a 2s  .  c o  m
 * 
 * @param url
 * @return
 * @throws Exception
 */
private static String getFileToString(String url) throws Exception {
    ClassLoader loader = SQLMap.class.getClassLoader();
    InputStream is = loader == null ? ClassLoader.getSystemResourceAsStream(url)
            : loader.getResourceAsStream(url);

    int size = is.available();
    byte[] dataByte = new byte[size];
    is.read(dataByte, 0, size);
    is.close();

    return new String(dataByte);
}

From source file:Utils.java

public static byte[] getBytes(InputStream is) throws IOException {

    int len;//  w w  w . j av  a 2s .c  om
    int size = 1024;
    byte[] buf;

    if (is instanceof ByteArrayInputStream) {
        size = is.available();
        buf = new byte[size];
        len = is.read(buf, 0, size);
    } else {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        buf = new byte[size];
        while ((len = is.read(buf, 0, size)) != -1)
            bos.write(buf, 0, len);
        buf = bos.toByteArray();
    }
    return buf;
}

From source file:com.vmware.identity.rest.core.client.RequestExecutor.java

private static String consumeContent(InputStream in) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream(in.available());

    final byte[] data = new byte[8196];
    int len = 0;/*from w ww  .  j  a  v  a 2  s  . co m*/

    while ((len = in.read(data)) > 0) {
        out.write(data, 0, len);
    }

    return out.toString();
}

From source file:Main.java

/**
 * @param s//from   www.  j a  va2 s  . co  m
 * @param b
 * @param startIdx
 * @param numBytes
 * @param timeout
 * @return
 * @throws IOException
 */
public static int inputStreamTimedRead(InputStream s, byte[] b, int startIdx, int numBytes, int timeout)
        throws IOException {
    int retval = -1;

    int i = 0;
    for (i = 0; i < timeout; i++) {
        if (s.available() > 0) {
            retval = s.read(b, startIdx, numBytes);
            break;
        }
        SystemClock.sleep(1000);
    }
    return retval;
}

From source file:resources.XmlToAnime.java

public static void ReadXml() {
    animes.clear();//from w  ww  . j a va 2 s . com
    if (sUrl.isEmpty() || sUrl == null) {
        throw new InternalError("Url should not be empty!");
    }

    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        //Document doc = (Document) dBuilder.parse(new URL(sUrl).openStream());
        //Document doc = (Document) dBuilder.parse

        InputStream input = getInput();
        if (input.available() > 0) {
            Document doc = (Document) dBuilder.parse(input);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("entry");

            for (int i = 0; i < nList.getLength(); i++) {
                Node nNode = nList.item(i);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Anime anime = new Anime();
                    Element eElement = (Element) nNode;
                    anime.setId(Integer.parseInt(eElement.getElementsByTagName("id").item(0).getTextContent()));
                    anime.setTitle(eElement.getElementsByTagName("title").item(0).getTextContent());
                    anime.setDescription(eElement.getElementsByTagName("synopsis").item(0).getTextContent());
                    anime.setEpisodes(Integer
                            .parseInt(eElement.getElementsByTagName("episodes").item(0).getTextContent()));
                    anime.setImageUrl(eElement.getElementsByTagName("image").item(0).getTextContent());
                    anime.setStartDate(eElement.getElementsByTagName("start_date").item(0).getTextContent());
                    anime.setEndDate(eElement.getElementsByTagName("end_date").item(0).getTextContent());

                    String temp = eElement.getElementsByTagName("status").item(0).getTextContent();
                    if (temp.toLowerCase().contains("finished")) {
                        anime.setStatus(AnimeStatus.FINISHED);
                    } else if (temp.toLowerCase().contains("currently")) {
                        anime.setStatus(AnimeStatus.CURRENTLY_AIRING);
                    }

                    anime.setAirDay(CalculateNextRelease.getAirDay(anime));
                    anime.setType(
                            Anime.TYPE.valueOf(eElement.getElementsByTagName("type").item(0).getTextContent()));
                    animes.add(anime);
                }
            }
        }

    } catch (SAXException | IOException | ParserConfigurationException e) {
        status = STATUS.ERROR;
        e.printStackTrace();
    }
}

From source file:com.github.hobbe.android.openkarotz.util.AssetUtils.java

/**
 * Load a JSON resource from the asset filename.
 * @param context the context// w ww. j a  va 2 s .co m
 * @param filename the name of the JSON object
 * @return the JSON object
 */
public static JSONObject loadJsonFromAsset(Context context, String filename) {
    JSONObject json = null;
    InputStream is = null;

    try {
        is = context.getAssets().open(filename);

        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);

        String content = new String(buffer, "UTF-8");
        json = new JSONObject(content);

    } catch (IOException e) {
        Log.e(LOG_TAG, "Could not load JSON asset " + filename, e);
        return null;
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Could not parse JSON from asset " + filename, e);
        return null;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // Ignored
            }
        }
    }

    return json;
}

From source file:Main.java

public static boolean checkIfDllInstalled(Context context) {
    boolean isInstalled = false;
    try {//from  w w  w  .ja  v a2s  .com
        InputStream inputStream = context.getAssets().open("Disdll.dll");
        File file = context.getFileStreamPath("Disdll.dll");
        if (file != null) {
            if (file.length() == inputStream.available()) {
                isInstalled = true;
            }
        }
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return isInstalled;
}

From source file:com.usefullc.platform.common.utils.IOUtils.java

/**
 * /*from w w  w .  j  ava 2 s.c  o m*/
 * 
 * @param path
 * @param fileName
 * @param response
 * @return
 */
public static void download(String path, String fileName, HttpServletResponse response) {
    try {

        if (StringUtils.isEmpty(path)) {
            throw new IllegalArgumentException("?");
        } else {
            File file = new File(path);
            if (!file.exists()) {
                throw new IllegalArgumentException("??");
            }
        }
        if (StringUtils.isEmpty(fileName)) {
            throw new IllegalArgumentException("???");
        }
        if (response == null) {
            throw new IllegalArgumentException("response ?");
        }

        // path
        File file = new File(path);

        // ??
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // response
        response.reset();

        // ??linux ?  linux utf-8,windows  GBK)
        String defaultEncoding = System.getProperty("file.encoding");
        if (defaultEncoding != null && defaultEncoding.equals("UTF-8")) {

            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1"));
        } else {
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
        }

        // responseHeader
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType("application/octet-stream");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

public static boolean installRingtone(final Context context, int resid, final String toneName) {

    String exStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
    String filename = toneName + ".mp3";
    File fileAlarms = new File(exStoragePath, "/Notifications");
    final File fileTone = new File(fileAlarms, filename);

    if (fileTone.exists())
        return false;

    boolean exists = fileAlarms.exists();
    if (!exists) {
        fileAlarms.mkdirs();/* w w  w .j  a v  a 2 s .  c o  m*/
    }

    if (fileTone.exists())
        return false;

    byte[] buffer = null;
    InputStream fIn = context.getResources().openRawResource(resid);
    int size = 0;

    try {
        size = fIn.available();
        buffer = new byte[size];
        fIn.read(buffer);
        fIn.close();
    } catch (IOException e) {
        return false;
    }

    FileOutputStream save;
    try {
        save = new FileOutputStream(fileTone);
        save.write(buffer);
        save.flush();
        save.close();
    } catch (FileNotFoundException e) {
        return false;
    } catch (IOException e) {
        return false;
    }

    MediaScannerConnection.scanFile(context, new String[] { fileTone.getAbsolutePath() }, null,
            new MediaScannerConnection.OnScanCompletedListener() {

                @Override
                public void onScanCompleted(String path, Uri uriTone) {

                    ContentValues values = new ContentValues();
                    values.put(MediaStore.MediaColumns.DATA, fileTone.getAbsolutePath());
                    values.put(MediaStore.MediaColumns.TITLE, toneName);
                    values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3");
                    values.put(MediaStore.Audio.Media.ARTIST, "zom");

                    //new
                    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
                    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
                    values.put(MediaStore.Audio.Media.IS_ALARM, true);
                    values.put(MediaStore.Audio.Media.IS_MUSIC, false);

                    // Insert it into the database
                    Uri newUri = context.getContentResolver().insert(uriTone, values);

                    //                RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);

                    //   Settings.System.putString(context.getContentResolver(),
                    //         Settings.System.RINGTONE, uri.toString());

                }
            });

    return true;
}