Example usage for java.io BufferedInputStream close

List of usage examples for java.io BufferedInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:JarBuilder.java

/** Add the contents of a directory that match a filter to the archive
 * @param dir the directory to add// ww w .j a v a2  s .co  m
 * @param parent the directory to add into
 * @param buffer a buffer that is 2048 bytes
 * @param filter the FileFilter to filter the files by
 * @return true on success, false on failure
 */
private boolean addDirectoryRecursiveHelper(File dir, String parent, byte[] buffer, FileFilter filter) {
    try {
        File[] files = dir.listFiles(filter);
        BufferedInputStream origin = null;

        if (files == null) // listFiles may return null if there's an IO error
            return true;
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                origin = new BufferedInputStream(new FileInputStream(files[i]), 2048);

                JarEntry entry = new JarEntry(makeName(parent, files[i].getName()));
                _output.putNextEntry(entry);

                int count;
                while ((count = origin.read(buffer, 0, 2048)) != -1) {
                    _output.write(buffer, 0, count);
                }
                origin.close();
            } else if (files[i].isDirectory()) {
                addDirectoryRecursiveHelper(files[i], makeName(parent, files[i].getName()), buffer, filter);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}

From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java

/**
 * /* w  w w .ja v a2s  .co  m*/
 * @param old      the file to be copied
 * @param newDir   the directory to move the file to
 * @return
 */
public int copyToDirectory(String old, String newDir) {
    File old_file = new File(old);
    File temp_dir = new File(newDir);
    byte[] data = new byte[BUFFER];
    int read = 0;

    if (old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()) {
        String file_name = old.substring(old.lastIndexOf("/"), old.length());
        File cp_file = new File(newDir + file_name);

        try {
            BufferedOutputStream o_stream = new BufferedOutputStream(new FileOutputStream(cp_file));
            BufferedInputStream i_stream = new BufferedInputStream(new FileInputStream(old_file));

            while ((read = i_stream.read(data, 0, BUFFER)) != -1)
                o_stream.write(data, 0, read);

            o_stream.flush();
            i_stream.close();
            o_stream.close();

        } catch (FileNotFoundException e) {
            Log.e("FileNotFoundException", e.getMessage());
            return -1;

        } catch (IOException e) {
            Log.e("IOException", e.getMessage());
            return -1;
        }

    } else if (old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) {
        String files[] = old_file.list();
        String dir = newDir + old.substring(old.lastIndexOf("/"), old.length());
        int len = files.length;

        if (!new File(dir).mkdir())
            return -1;

        for (int i = 0; i < len; i++)
            copyToDirectory(old + "/" + files[i], dir);

    } else if (!temp_dir.canWrite())
        return -1;

    return 0;
}

From source file:jp.co.opentone.bsol.linkbinder.view.logo.ProjectLogoManager.java

/**
 * ??(??)??.//from   ww  w .j  av a  2  s .com
 *
 * @param logoFile ??
 * @return (??)
 */
private ProjectLogo getLogoData(String logoFile) {
    ProjectLogo result = null;
    BufferedInputStream bis = null;

    try {
        File f = new File(logoFile);
        long lastModifiled = f.lastModified();
        byte[] imageData = new byte[(int) f.length()];
        bis = new BufferedInputStream(new FileInputStream(logoFile));
        bis.read(imageData);

        result = new ProjectLogo();
        result.setImage(imageData);
        result.setLastModified(lastModifiled);
    } catch (FileNotFoundException e) {
        log.warn("????? [" + logoFile + "]");
    } catch (IOException e) {
        log.error("File I/O error[" + logoFile + "]", e);
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                log.error("File close error.[" + logoFile + "]", e);
            }
        }
    }
    return result;
}

From source file:edu.stanford.epad.epadws.handlers.dicom.DownloadUtil.java

/**
 * Method to download file in resources folder
 * //from w  w  w . java  2 s  .c o m
 * @param httpResponse
 * @param seriesReference
 * @param username
 * @param sessionID
 * @throws Exception
 */
public static void downloadResource(String relativePath, HttpServletResponse httpResponse, String username,
        String sessionID) throws Exception {
    String resourcesPath = EPADConfig.getEPADWebServerResourcesDir();
    File file = new File(resourcesPath + "/" + relativePath);
    if (!file.exists())
        throw new Exception("Requested resource " + relativePath + " does not exist");

    if (file.isDirectory())
        throw new Exception("Requested resource " + relativePath + " is a folder");

    httpResponse.setContentType("application/zip");
    httpResponse.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");

    OutputStream out = null;
    BufferedInputStream fr = null;
    try {
        out = httpResponse.getOutputStream();
        fr = new BufferedInputStream(new FileInputStream(file));

        byte buffer[] = new byte[0xffff];
        int b;
        while ((b = fr.read(buffer)) != -1)
            out.write(buffer, 0, b);
    } catch (Exception e) {
        log.warning("Error streaming file", e);
        throw e;
    } finally {
        if (fr != null)
            fr.close();
    }
}

From source file:Main.java

public static String getCharset(File file) {
    String charset = "GBK";
    byte[] first3Bytes = new byte[3];
    try {/*from  w  ww.  j  a v a 2 s .  com*/
        boolean checked = false;
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        bis.mark(0);
        int read = bis.read(first3Bytes, 0, 3);
        if (read == -1)
            return charset;
        if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
            charset = "UTF-16LE";
            checked = true;
        } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
            charset = "UTF-16BE";
            checked = true;
        } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB
                && first3Bytes[2] == (byte) 0xBF) {
            charset = "UTF-8";
            checked = true;
        }
        bis.reset();
        if (!checked) {
            int loc = 0;
            while ((read = bis.read()) != -1) {
                loc++;
                if (read >= 0xF0)
                    break;
                if (0x80 <= read && read <= 0xBF)
                    break;
                if (0xC0 <= read && read <= 0xDF) {
                    read = bis.read();
                    if (0x80 <= read && read <= 0xBF)
                        continue;
                    else
                        break;
                } else if (0xE0 <= read && read <= 0xEF) {
                    read = bis.read();
                    if (0x80 <= read && read <= 0xBF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            charset = "UTF-8";
                            break;
                        } else
                            break;
                    } else
                        break;
                }
            }
        }
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return charset;
}

From source file:org.caboclo.clients.OneDriveClient.java

@Override
public void getFile(File file, String child) throws IOException {
    String source = getFileID(child);
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(source);
    HttpResponse response = httpclient.execute(httpget);
    //System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {/*from  www  .j a v  a  2 s  . co m*/
            InputStream instream = entity.getContent();
            BufferedInputStream bis = new BufferedInputStream(instream);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            int inByte;
            while ((inByte = bis.read()) != -1) {
                bos.write(inByte);
            }
            bis.close();
            bos.close();
        } catch (IOException ex) {
            throw ex;
        } catch (IllegalStateException ex) {
            httpget.abort();
            throw ex;
        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:SendMp3.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String fileName = (String) request.getParameter("file");
    if (fileName == null || fileName.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in SendMp3 servlet.");

    if (fileName.indexOf(".mp3") == -1)
        fileName = fileName + ".mp3";

    String mp3Dir = getServletContext().getInitParameter("mp3-dir");
    if (mp3Dir == null || mp3Dir.equals(""))
        throw new ServletException("Invalid or non-existent mp3Dir context-param.");

    ServletOutputStream stream = null;/*  w  ww  .j  av a2  s.  c  o m*/
    BufferedInputStream buf = null;
    try {

        stream = response.getOutputStream();
        File mp3 = new File(mp3Dir + "/" + fileName);

        //set response headers
        response.setContentType("audio/mpeg");

        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

        response.setContentLength((int) mp3.length());

        FileInputStream input = new FileInputStream(mp3);
        buf = new BufferedInputStream(input);
        int readBytes = 0;
        //read from the file; write to the ServletOutputStream
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
    } catch (IOException ioe) {
        throw new ServletException(ioe.getMessage());
    } finally {
        if (stream != null)
            stream.close();
        if (buf != null)
            buf.close();
    }
}

From source file:com.music.mybarr.activities.ExampleActivity.java

private void next(final boolean manualPlay) {
    if (player != null) {
        player.stop();// w w  w .  java 2s.  co m
        player.release();
        player = null;
    }

    final Track track = trackQueue.poll();
    if (trackQueue.size() < 3) {
        Log.i(TAG, "Track queue depleted, loading more tracks");
        LoadMoreTracks();
    }

    if (track == null) {
        Log.e(TAG, "Track is null!  Size of queue: " + trackQueue.size());
        return;
    }

    // Load the next track in the background and prep the player (to start buffering)
    // Do this in a bkg thread so it doesn't block the main thread in .prepare()
    AsyncTask<Track, Void, Track> task = new AsyncTask<Track, Void, Track>() {
        @Override
        protected Track doInBackground(Track... params) {
            Track track = params[0];
            try {
                player = rdio.getPlayerForTrack(track.key, null, manualPlay);
                player.prepare();
                player.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        next(false);
                    }
                });
                player.start();
            } catch (Exception e) {
                Log.e("Test", "Exception " + e);
            }
            return track;
        }

        @Override
        protected void onPostExecute(Track track) {
            updatePlayPause(true);
        }
    };
    task.execute(track);

    // Fetch album art in the background and then update the UI on the main thread
    AsyncTask<Track, Void, Bitmap> artworkTask = new AsyncTask<Track, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(Track... params) {
            Track track = params[0];
            try {
                String artworkUrl = track.albumArt.replace("square-200", "square-600");
                Log.i(TAG, "Downloading album art: " + artworkUrl);
                Bitmap bm = null;
                try {
                    URL aURL = new URL(artworkUrl);
                    URLConnection conn = aURL.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bm = BitmapFactory.decodeStream(bis);
                    bis.close();
                    is.close();
                } catch (IOException e) {
                    Log.e(TAG, "Error getting bitmap", e);
                }
                return bm;
            } catch (Exception e) {
                Log.e(TAG, "Error downloading artwork", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap artwork) {
            if (artwork != null) {
                albumArt.setImageBitmap(artwork);
            } else
                albumArt.setImageResource(R.drawable.blank_album_art);
        }
    };
    artworkTask.execute(track);

    Toast.makeText(this, String.format(getResources().getString(R.string.now_playing), track.trackName,
            track.albumName, track.artistName), Toast.LENGTH_LONG).show();
}

From source file:com.bigdata.dastor.thrift.server.DastorThriftServer.java

public String get_string_property(String propertyName) {
    if (propertyName.equals("cluster name")) {
        return DatabaseDescriptor.getClusterName();
    } else if (propertyName.equals("config file")) {
        String filename = DatabaseDescriptor.getConfigFileName();
        try {/*from   w  w w .j  a  v a 2  s. co m*/
            StringBuilder fileData = new StringBuilder(8192);
            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(filename));
            byte[] buf = new byte[1024];
            int numRead;
            while ((numRead = stream.read(buf)) != -1) {
                String str = new String(buf, 0, numRead);
                fileData.append(str);
            }
            stream.close();
            return fileData.toString();
        } catch (IOException e) {
            return "file not found!";
        }
    } else if (propertyName.equals(TOKEN_MAP)) {
        return JSONValue.toJSONString(storageService.getStringEndpointMap());
    } else if (propertyName.equals("version")) {
        return Constants.VERSION;
    } else {
        return "?";
    }
}