Example usage for java.io BufferedInputStream BufferedInputStream

List of usage examples for java.io BufferedInputStream BufferedInputStream

Introduction

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

Prototype

public BufferedInputStream(InputStream in) 

Source Link

Document

Creates a BufferedInputStream and saves its argument, the input stream in, for later use.

Usage

From source file:Main.java

public void playSound(final String filename) throws Exception {
    InputStream audioSrc = this.getClass().getResourceAsStream(filename);

    InputStream bufferedIn = new BufferedInputStream(audioSrc);
    audioStream = AudioSystem.getAudioInputStream(bufferedIn);

    audioFormat = audioStream.getFormat();

    DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
    sourceLine = (SourceDataLine) AudioSystem.getLine(info);
    sourceLine.open(audioFormat);/* w ww  . j a  va 2  s  . c  o  m*/

    sourceLine.start();
    running = true;

    while (running) {
        audioStream.mark(BUFFER_SIZE);
        int nBytesRead = 0;
        byte[] abData = new byte[BUFFER_SIZE];
        while (nBytesRead != -1) {
            try {
                nBytesRead = audioStream.read(abData, 0, abData.length);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (nBytesRead >= 0) {
                sourceLine.write(abData, 0, nBytesRead);
            }
        }
        if (running)
            audioStream.reset();
    }
    sourceLine.drain();
    sourceLine.close();
}

From source file:com.ms.commons.test.tool.util.AutoImportProjectTaskUtil.java

@SuppressWarnings({ "unchecked", "deprecation" })
public static Task wrapAutoImportTask(final File project, final Task oldTask) {
    InputStream fis = null;/*from w ww . j ava 2 s  . co  m*/
    try {
        fis = new BufferedInputStream(project.toURL().openStream());
        SAXBuilder b = new SAXBuilder();
        Document document = b.build(fis);

        List<Element> elements = XPath.selectNodes(document, "/project/build/dependencies/include");

        List<String> addList = new ArrayList<String>(importList);
        if (elements != null) {
            for (Element ele : elements) {
                String uri = ele.getAttribute("uri").getValue().trim().toLowerCase();
                if (importList.contains(uri)) {
                    addList.remove(uri);
                }
            }
        }

        if (addList.size() > 0) {
            System.err.println("Add projects:" + addList);

            List<Element> testElements = XPath.selectNodes(document,
                    "/project/build[@profile='TEST']/dependencies");
            Element testEle;
            if ((testElements == null) || (testElements.size() == 0)) {
                Element buildEle = new Element("build");
                buildEle.setAttribute("profile", "TEST");

                Element filesetsEle = new Element("filesets");
                filesetsEle.setAttribute("name", "java.resdirs");
                Element excludeEle = new Element("exclude");
                excludeEle.setAttribute("fileset", "java.configdir");
                filesetsEle.addContent(excludeEle);

                testEle = new Element("dependencies");

                buildEle.addContent(Arrays.asList(filesetsEle, testEle));

                ((Element) XPath.selectNodes(document, "/project").get(0)).addContent(buildEle);
            } else {
                testEle = testElements.get(0);
            }

            for (String add : addList) {
                Element e = new Element("include");
                e.setAttribute("uri", add);
                testEle.addContent(e);
            }

            String newF = project.getAbsolutePath() + ".new";

            XMLOutputter xmlOutputter = new XMLOutputter();
            Writer writer = new BufferedWriter(new FileWriter(newF));
            xmlOutputter.output(document, writer);
            writer.flush();
            FileUtil.closeCloseAbleQuitly(writer);

            final File newFile = new File(newF);
            return new Task() {

                public void finish() {
                    boolean hasError = false;
                    File backUpFile = new File(project.getAbsoluteFile() + ".backup");
                    try {
                        FileUtils.copyFile(project, backUpFile);
                        FileUtils.copyFile(newFile, project);

                        oldTask.finish();
                    } catch (Exception e) {
                        hasError = true;
                        e.printStackTrace();
                    } finally {
                        try {
                            FileUtils.copyFile(backUpFile, project);
                        } catch (IOException e) {
                            hasError = true;
                            e.printStackTrace();
                        }
                        newFile.delete();
                        backUpFile.delete();
                    }
                    if (hasError) {
                        System.exit(-1);
                    }
                }
            };
        }

        return oldTask;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        FileUtil.closeCloseAbleQuitly(fis);
    }
}

From source file:info.tongrenlu.android.helper.HttpHelper.java

static public JSONObject loadJSON(String url) {
    HttpURLConnection connection = null;
    JSONObject json = null;/*from  ww  w . ja v a2s.  c  o m*/
    InputStream is = null;

    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(5000);

        is = new BufferedInputStream(connection.getInputStream());
        json = new JSONObject(convertStreamToString(is));
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (JSONException je) {
        je.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        if (connection != null) {
            connection.disconnect();
        }
    }

    return json;
}

From source file:com.ms.commons.test.datareader.impl.XmlReaderUtil.java

@SuppressWarnings("unchecked")
public static MemoryDatabase readDocument(String file) {
    try {/*w w w. ja  v  a  2 s  .  co m*/
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new BufferedInputStream(new FileInputStream(getAbsolutedPath(file))));
        List<Element> elements = doc.getRootElement().elements("table");
        List<MemoryTable> tableList = new ArrayList<MemoryTable>();
        for (Element tableE : elements) {
            tableList.add(readTable(tableE));
        }

        MemoryDatabase database = new MemoryDatabase();
        database.setTableList(tableList);
        return database;
    } catch (FileNotFoundException e) {
        throw new ResourceNotFoundException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static InputStream getInputStream(Context context, Uri uri) throws IOException {
    InputStream inputStream;//from w  w  w .j  a va  2  s .  c om
    if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme())
            || ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme())
            || ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
        inputStream = context.getContentResolver().openInputStream(uri);
    } else {
        URLConnection urlConnection = new URL(uri.toString()).openConnection();
        urlConnection.setConnectTimeout(URLCONNECTION_CONNECTION_TIMEOUT_MS);
        urlConnection.setReadTimeout(URLCONNECTION_READ_TIMEOUT_MS);
        inputStream = urlConnection.getInputStream();
    }
    return new BufferedInputStream(inputStream);
}

From source file:Main.java

public static void unzip(URL _url, URL _dest, boolean _remove_top) {
    int BUFFER_SZ = 2048;
    File file = new File(_url.getPath());

    String dest = _dest.getPath();
    new File(dest).mkdir();

    try {/* w ww .j ava2 s .co  m*/
        ZipFile zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();

            if (_remove_top)
                currentEntry = currentEntry.substring(currentEntry.indexOf('/'), currentEntry.length());

            File destFile = new File(dest, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();

            // create the parent directory structure if needed
            destinationParent.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream is;
                is = new BufferedInputStream(zip.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER_SZ];

                // write the current file to disk
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedOutputStream dst = new BufferedOutputStream(fos, BUFFER_SZ);

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER_SZ)) != -1) {
                    dst.write(data, 0, currentByte);
                }
                dst.flush();
                dst.close();
                is.close();
            }
            /*
            if (currentEntry.endsWith(".zip"))
            {
            // found a zip file, try to open
            extractFolder(destFile.getAbsolutePath());
            }*/
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:Main.java

/** Reads the specified file into a string
 * @param filePath the path to the file that should be read
 * @return the content of the specified file as a string or an empty string if the file does not exist 
 * @throws IOException *///from   ww w  . j a  v  a  2s .c o  m
public static String readFileAsString(String filePath) throws IOException {
    File file = new File(filePath);
    if (!file.exists()) {
        return "";
    }

    byte[] buffer = new byte[(int) new File(filePath).length()];

    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
    bufferedInputStream.read(buffer);
    bufferedInputStream.close();

    return new String(buffer);
}

From source file:com.grosscommerce.ICEcat.utilities.Downloader.java

public static void download(String urlFrom, String login, String pwd, OutputStream destStream)
        throws Exception {
    try {//from   ww  w  .  j  av a2s.c  om
        HttpURLConnection uc = prepareConnection(urlFrom, login, pwd);

        uc.connect();

        if (uc.getResponseCode() != HttpURLConnection.HTTP_OK) {
            Logger.getLogger(Downloader.class.getName()).log(Level.INFO, "Error, code: {0}, message {1}",
                    new Object[] { uc.getResponseCode(), uc.getResponseMessage() });

            return;
        }

        BufferedInputStream is = null;

        if ((uc.getContentEncoding() != null && uc.getContentEncoding().toLowerCase().equals("gzip"))
                || uc.getContentType() != null && uc.getContentType().toLowerCase().contains("gzip")) {
            is = new BufferedInputStream(new GZIPInputStream(uc.getInputStream()));

            Logger.getLogger(Downloader.class.getName()).log(Level.INFO, "Will download gzip data from: {0}",
                    urlFrom);
        } else {
            is = new BufferedInputStream(uc.getInputStream());

            Logger.getLogger(Downloader.class.getName()).log(Level.INFO,
                    "Will download not compressed data from:{0}", urlFrom);
        }

        StreamsHelper.copy(is, destStream);
        destStream.flush();

    } catch (Exception ex) {
        Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, "URL: " + urlFrom, ex);

        throw ex;
    }
}

From source file:com.indexoutofbounds.util.ClassPathInputStreamUtils.java

/**
 * Creates an InputStream from the path which can be either something on
 * the file system, a remote system, or a classpath entry.
 * @param path//from  w  w w. j  a  v  a  2s . c om
 * @return
 * @throws Exception
 */
public final static InputStream getInputStream(final String path) throws IOException {

    if (StringUtils.isEmpty(path)) {
        throw new IOException("Unable to locate empty config file parameter");
    }

    final URL url = locateURL(path);
    if (url == null) {
        throw new IOException("Unable to locate config file: " + path);
    }

    try {

        return new BufferedInputStream(url.openStream());
    } catch (IOException e) {
        throw new IOException("Unable to open config file: " + path + ", " + e.getLocalizedMessage());
    }
}

From source file:Main.java

/**
 * Read bytes from an HTTP connection.//ww  w. j a va2s.c  om
 * @param connection the connection to read from.
 * @return an array of the bytes read.
 * @throws Exception if any error occurs.
 */
static byte[] readBytes(HttpURLConnection connection) throws Exception {
    return readBytes(new BufferedInputStream(connection.getInputStream()));
}