Example usage for java.io BufferedInputStream read

List of usage examples for java.io BufferedInputStream read

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:controller.LoadImageServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from w w  w  . j  av a 2s.  c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String iid = request.getParameter("param1");
    byte[] sImageBytes;
    try {

        Connection con = JdbcConnection.getConnection();
        String Query = "SELECT image FROM user WHERE email ='" + iid + "';";
        System.out.println("Query is" + Query);
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(Query);
        System.out.println("..........1");
        String name = "client_2";
        if (rs.next()) {

            sImageBytes = rs.getBytes("image");

            response.setContentType("image/jpeg");
            response.setContentLength(sImageBytes.length);
            // Give the name of the image in the name variable in the below line   
            response.setHeader("Content-Disposition", "inline; filename=\"" + name + "\"");

            BufferedInputStream input = new BufferedInputStream(new ByteArrayInputStream(sImageBytes));
            BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());

            byte[] buffer = new byte[8192];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
                System.out.println(".......3");
            }
            output.flush();
        }
    } catch (Exception ex) {
        System.out.println("error :" + ex);
    }
}

From source file:com.bradmcevoy.io.FileUtils.java

public String read(InputStream in) {
    try {/*from w  w w .j  av  a 2  s . c o  m*/
        BufferedInputStream bin = new BufferedInputStream(in);
        int s;
        byte[] buf = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while ((s = bin.read(buf)) > -1) {
            sb.append(new String(buf, 0, s));
        }
        return sb.toString();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:io.dstream.tez.utils.ClassPathUtils.java

/**
 *
 * @param source//from   ww  w  .  ja  va  2  s  . c om
 * @param lengthOfOriginalPath
 * @param target
 * @throws IOException
 */
private static void add(File source, int lengthOfOriginalPath, JarOutputStream target) throws IOException {
    BufferedInputStream in = null;
    try {
        String path = source.getAbsolutePath();
        path = path.substring(lengthOfOriginalPath);

        if (source.isDirectory()) {
            String name = path.replace("\\", "/");
            if (!name.isEmpty()) {
                if (!name.endsWith("/")) {
                    name += "/";
                }
                JarEntry entry = new JarEntry(name.substring(1)); // avoiding absolute path warning
                target.putNextEntry(entry);
                target.closeEntry();
            }

            for (File nestedFile : source.listFiles()) {
                add(nestedFile, lengthOfOriginalPath, target);
            }

            return;
        }

        JarEntry entry = new JarEntry(path.replace("\\", "/").substring(1)); // avoiding absolute path warning
        entry.setTime(source.lastModified());
        try {
            target.putNextEntry(entry);
            in = new BufferedInputStream(new FileInputStream(source));

            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1) {
                    break;
                }
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        } catch (Exception e) {
            String message = e.getMessage();
            if (message != null) {
                if (!message.toLowerCase().contains("duplicate")) {
                    throw new IllegalStateException(e);
                }
                logger.warn(message);
            } else {
                throw new IllegalStateException(e);
            }
        }
    } finally {
        if (in != null)
            in.close();
    }
}

From source file:buildhappy.tools.DownloadFile.java

/**
 * URL//from   w w w . ja  v a 2 s .  com
 */
public String downloadFile(String url) {
    String filePath = null;
    //1.?HttpClient??
    HttpClient client = new HttpClient();
    //5s
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    //2.?GetMethod?
    GetMethod getMethod = new GetMethod(url);
    //get5s
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
    //??
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

    //3.http get 
    try {
        int statusCode = client.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed:" + getMethod.getStatusLine());
            filePath = null;
        }
        //4.?HTTP?
        InputStream in = getMethod.getResponseBodyAsStream();
        BufferedInputStream buffIn = new BufferedInputStream(in);
        //byte[] responseBody = null;
        String responseBody = null;
        StringBuffer strBuff = new StringBuffer();
        byte[] b = new byte[1024];
        int readByte = 0;
        while ((readByte = buffIn.read(b)) != -1) {
            strBuff.append(new String(b));
        }
        responseBody = strBuff.toString();
        //buffIn.read(responseBody, off, len)
        //byte[] responseBody = getMethod.getResponseBody();
        //?url????
        filePath = "temp\\" + getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue());
        System.out.println(filePath + "--size:" + responseBody.length());
        saveToLocal(responseBody.getBytes(), filePath);
    } catch (HttpException e) {
        System.out.println("check your http address");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //
        getMethod.releaseConnection();
    }
    return filePath;
}

From source file:averroes.JarFile.java

/**
 * Add the given file with the given entry name to this JAR file.
 * //from w w  w .  j  a v  a2 s . co m
 * @param source
 * @param entryName
 * @throws IOException
 */
public void add(File source, String entryName) throws IOException {
    JarEntry entry = new JarEntry(entryName);
    entry.setTime(source.lastModified());
    getJarOutputStream().putNextEntry(entry);
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));

    byte[] buffer = new byte[1024];
    int len;
    while ((len = in.read(buffer)) != -1) {
        getJarOutputStream().write(buffer, 0, len);
    }
    getJarOutputStream().closeEntry();
    in.close();
}

From source file:com.LogicTree.app.Florida511.AudioDownloader.java

/**
 * @param filename//from ww  w. ja va2s.com
 * @param is
 */
void createExternalStoragePrivateFile(String filename, InputStream is) {
    // Create a path where we will place our private file on external
    // storage.
    File file = new File(cacheDir, filename);

    try {
        BufferedInputStream bi = new BufferedInputStream(is);
        OutputStream os = new FileOutputStream(file);
        byte[] data = new byte[16384];
        int count;
        while ((count = bi.read(data)) != -1) {
            os.write(data, 0, count);
        }
        bi.close();
        is.close();
        os.close();
    } catch (IOException e) {
        // Unable to create file, likely because external storage is
        // not currently mounted.
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
}

From source file:org.jboss.ejb3.packagemanager.retriever.impl.HttpPackageRetriever.java

/**
 * @see org.jboss.ejb3.packagemanager.retriever.PackageRetriever#retrievePackage(PackageManagerContext, URL)
 *//*from  w  w  w .j a  v  a2  s . c o m*/
@Override
public File retrievePackage(PackageManagerContext pkgMgrCtx, URL packagePath) throws PackageRetrievalException {
    if (!packagePath.getProtocol().equals("http")) {
        throw new PackageRetrievalException("Cannot handle " + packagePath);
    }
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(packagePath.toExternalForm());
    HttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet);
    } catch (Exception e) {
        throw new PackageRetrievalException("Exception while retrieving package " + packagePath, e);
    }
    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new PackageRetrievalException("Http retrieval wasn't successful, returned status code  "
                + httpResponse.getStatusLine().getStatusCode());
    }
    HttpEntity httpEntity = httpResponse.getEntity();

    try {
        // TODO: should this tmp be deleted on exit?
        File tmpPkgFile = File.createTempFile("tmp", ".jar",
                pkgMgrCtx.getPackageManagerEnvironment().getPackageManagerTmpDir());
        FileOutputStream fos = new FileOutputStream(tmpPkgFile);
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            bos = new BufferedOutputStream(fos);
            InputStream is = httpEntity.getContent();
            bis = new BufferedInputStream(is);
            byte[] content = new byte[4096];
            int length;
            while ((length = bis.read(content)) != -1) {
                bos.write(content, 0, length);
            }
            bos.flush();
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (bis != null) {
                bis.close();
            }
        }
        return tmpPkgFile;

    } catch (IOException ioe) {
        throw new PackageRetrievalException("Could not process the retrieved package", ioe);
    }
    // TODO: I need to read the HttpClient 4.x javadocs to figure out the API for closing the
    // Http connection

}

From source file:com.tesshu.subsonic.client.sample4_music_andmovie.StreamDownloadAndPlayWithThreadApplication.java

@Override
public void start(Stage stage) throws Exception {

    Search2Controller search2 = context.getBean(Search2Controller.class);

    StreamController streamController = context.getBean(StreamController.class);

    SuccessObserver callback = context.getBean(SuccessObserver.class);

    SearchResult2 result2 = search2.get("e", null, null, null, null, 1, null, null);

    List<Child> songs = result2.getSongs();

    File tmpDirectory = new File(tmpPath);
    tmpDirectory.mkdir();/* w ww  . jav  a2s .  c o m*/

    int maxBitRate = 256;

    Child song = songs.get(0);

    new Thread(new Runnable() {
        public void run() {
            try {

                streamController.stream(song, maxBitRate, format, null, null, null, null,

                        (subject, inputStream, contentLength) -> {

                            File dir = new File(
                                    tmpPath + "/" + song.getPath().replaceAll("([^/]+?)?$", StringUtils.EMPTY));
                            dir.mkdirs();

                            file = new File(tmpPath + "/"
                                    + song.getPath().replaceAll("([^.]+?)?$", StringUtils.EMPTY) + format);

                            try {

                                FileOutputStream fos = new FileOutputStream(file);
                                BufferedInputStream reader = new BufferedInputStream(inputStream);

                                byte buf[] = new byte[256];
                                int len;
                                while ((len = reader.read(buf)) != -1) {
                                    fos.write(buf, 0, len);
                                }
                                fos.flush();
                                fos.close();
                                reader.close();
                                inputStream.close();

                                LOG.info("download finished");

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }, callback);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    LOG.info("download thread start");

    new Thread(new Runnable() {
        public void run() {
            while (file == null || file.getPath() == null) {
                LOG.info("wait file writing.");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                String path = Paths.get(file.getPath()).toUri().toString();
                Group root = new Group();
                Scene scene = new Scene(root, 640, 480);
                Media media = new Media(path);
                MediaPlayer player = new MediaPlayer(media);
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            while (MediaPlayer.Status.READY != player.getStatus()) {
                                LOG.info(player.getStatus() + " : " + path);
                                LOG.info(media.errorProperty());
                                Thread.sleep(1000);
                                if (MediaPlayer.Status.PLAYING == player.getStatus()) {
                                    LOG.info(player.getStatus() + " : " + path);
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                MediaView view = new MediaView(player);
                ((Group) scene.getRoot()).getChildren().add(view);

                Platform.runLater(() -> {
                    stage.setScene(scene);
                    stage.show();
                    player.play();
                });

            }
        }
    }).start();

}

From source file:eu.scape_project.hawarp.webarchive.PayloadContent.java

private byte[] inputStreamToByteArray() {
    try {/*from w  w w .  j ava2 s .  com*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedInputStream buffis = new BufferedInputStream(inputStream);
        BufferedOutputStream buffos = new BufferedOutputStream(baos);
        byte[] tempBuffer = new byte[8192];
        int bytesRead;
        boolean firstByteArray = true;
        while ((bytesRead = buffis.read(tempBuffer)) != -1) {
            buffos.write(tempBuffer, 0, bytesRead);
            if (doPayloadIdentification && firstByteArray && tempBuffer != null && bytesRead > 0) {
                identified = identifyPayloadType(tempBuffer);
            }
            firstByteArray = false;
        }
        //buffis.close();
        buffos.flush();
        buffos.close();

        return baos.toByteArray();
    } catch (IOException ex) {
        LOG.error("Error while trying to read payload content", ex);
        this.error = true;
        return null;
    }
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * GZipping a string./*w  ww .ja  v a 2s  .c o m*/
 * 
 * @param data the content to be gzipped.
 * @param filename the name for the file.
 * @return a ByteArrayDataSource.
 */
protected ByteArrayDataSource compressFile(File fileName) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gz = new GZIPOutputStream(out);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(fileName));
    byte[] dataBuffer = new byte[512];
    while ((bufferedInputStream.read(dataBuffer)) != -1) {
        gz.write(dataBuffer);
    }
    gz.close();
    bufferedInputStream.close();
    ByteArrayDataSource dataSrc = new ByteArrayDataSource(out.toByteArray(), "application/x-gzip");
    return dataSrc;
}