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:com.lidroid.xutils.http.client.callback.FileDownloadHandler.java

public File handleEntity(HttpEntity entity, RequestCallBackHandler callBackHandler, String target,
        boolean isResume, String responseFileName) throws IOException {
    if (entity == null || TextUtils.isEmpty(target)) {
        return null;
    }/*from   w w w .j a  v  a  2  s  .com*/

    File targetFile = new File(target);

    if (!targetFile.exists()) {
        targetFile.createNewFile();
    }

    long current = 0;
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;

    try {

        if (isResume) {
            current = targetFile.length();
            fileOutputStream = new FileOutputStream(target, true);
        } else {
            fileOutputStream = new FileOutputStream(target);
        }

        long total = entity.getContentLength() + current;

        if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) {
            return null;
        }

        inputStream = entity.getContent();
        BufferedInputStream bis = new BufferedInputStream(inputStream);

        byte[] tmp = new byte[4096];
        int len;
        while ((len = bis.read(tmp)) != -1) {
            fileOutputStream.write(tmp, 0, len);
            current += len;
            if (callBackHandler != null) {
                if (!callBackHandler.updateProgress(total, current, false)) {
                    return targetFile;
                }
            }
        }
        fileOutputStream.flush();
        if (callBackHandler != null) {
            callBackHandler.updateProgress(total, current, true);
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }

    if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) {
        File newFile = new File(targetFile.getParent(), responseFileName);
        targetFile.renameTo(newFile);
        return newFile;
    } else {
        return targetFile;
    }
}

From source file:com.dongfang.net.http.client.callback.FileDownloadHandler.java

public File handleEntity(HttpEntity entity, RequestCallBackHandler callBackHandler, String target,
        boolean isResume, String responseFileName) throws IOException {
    if (entity == null || TextUtils.isEmpty(target)) {
        return null;
    }/*from w  w w  . j ava2  s. c  o  m*/

    File targetFile = new File(target);

    if (!targetFile.exists()) {
        targetFile.createNewFile();
    }

    long current = 0;
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;

    try {

        if (isResume) {
            current = targetFile.length();
            fileOutputStream = new FileOutputStream(target, true);
        } else {
            fileOutputStream = new FileOutputStream(target);
        }

        long total = entity.getContentLength() + current;

        if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) {
            return targetFile;
        }

        inputStream = entity.getContent();
        BufferedInputStream bis = new BufferedInputStream(inputStream);

        byte[] tmp = new byte[4096];
        int len;
        while ((len = bis.read(tmp)) != -1) {
            fileOutputStream.write(tmp, 0, len);
            current += len;
            if (callBackHandler != null) {
                if (!callBackHandler.updateProgress(total, current, false)) {
                    return targetFile;
                }
            }
        }
        fileOutputStream.flush();
        if (callBackHandler != null) {
            callBackHandler.updateProgress(total, current, true);
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }

    if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) {
        File newFile = new File(targetFile.getParent(), responseFileName);
        while (newFile.exists()) {
            newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName);
        }
        return targetFile.renameTo(newFile) ? newFile : targetFile;
    } else {
        return targetFile;
    }
}

From source file:com.lidroid.xutils.http.callback.FileDownloadHandler.java

public File handleEntity(HttpEntity entity, RequestCallBackHandler callBackHandler, String target,
        boolean isResume, String responseFileName) throws IOException {
    if (entity == null || TextUtils.isEmpty(target)) {
        return null;
    }// w  ww .  ja  v  a 2 s. c o m

    File targetFile = new File(target);

    if (!targetFile.exists()) {
        File dir = targetFile.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        targetFile.createNewFile();
    }

    long current = 0;
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;

    try {

        if (isResume) {
            current = targetFile.length();
            fileOutputStream = new FileOutputStream(target, true);
        } else {
            fileOutputStream = new FileOutputStream(target);
        }

        long total = entity.getContentLength() + current;

        if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) {
            return targetFile;
        }

        inputStream = entity.getContent();
        BufferedInputStream bis = new BufferedInputStream(inputStream);

        byte[] tmp = new byte[4096];
        int len;
        while ((len = bis.read(tmp)) != -1) {
            fileOutputStream.write(tmp, 0, len);
            current += len;
            if (callBackHandler != null) {
                if (!callBackHandler.updateProgress(total, current, false)) {
                    return targetFile;
                }
            }
        }
        fileOutputStream.flush();
        if (callBackHandler != null) {
            callBackHandler.updateProgress(total, current, true);
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }

    if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) {
        File newFile = new File(targetFile.getParent(), responseFileName);
        while (newFile.exists()) {
            newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName);
        }
        return targetFile.renameTo(newFile) ? newFile : targetFile;
    } else {
        return targetFile;
    }
}

From source file:com.creditease.utilframe.http.client.entity.FileUploadEntity.java

@SuppressWarnings("resource")
@Override//from  www .  ja  v  a2s.  c  o  m
public void writeTo(OutputStream outStream) throws IOException {
    if (outStream == null) {
        throw new IllegalArgumentException("Output stream may not be null");
    }
    BufferedInputStream inStream = null;
    try {
        inStream = new BufferedInputStream(new FileInputStream(this.file));
        byte[] tmp = new byte[4096];
        int len;
        while ((len = inStream.read(tmp)) != -1) {
            outStream.write(tmp, 0, len);
            uploadedSize += len;
            if (callBackHandler != null) {
                if (!callBackHandler.updateProgress(fileSize, uploadedSize, false)) {
                    IOUtils.closeQuietly(inStream);
                    throw new InterruptedIOException("cancel");
                }
            }
        }
        outStream.flush();
        if (callBackHandler != null) {
            callBackHandler.updateProgress(fileSize, uploadedSize, true);
        }
    } finally {
        IOUtils.closeQuietly(inStream);
    }
}

From source file:cn.isif.util_plus.http.client.entity.FileUploadEntity.java

@Override
public void writeTo(OutputStream outStream) throws IOException {
    if (outStream == null) {
        throw new IllegalArgumentException("Output stream may not be null");
    }//w w w. j a  va2s .c om
    BufferedInputStream inStream = null;
    try {
        inStream = new BufferedInputStream(new FileInputStream(this.file));
        byte[] tmp = new byte[4096];
        int len;
        while ((len = inStream.read(tmp)) != -1) {
            outStream.write(tmp, 0, len);
            uploadedSize += len;
            if (callBackHandler != null) {
                if (!callBackHandler.updateProgress(fileSize, uploadedSize, false)) {
                    throw new InterruptedIOException("cancel");
                }
            }
        }
        outStream.flush();
        if (callBackHandler != null) {
            callBackHandler.updateProgress(fileSize, uploadedSize, true);
        }
    } finally {
        IOUtils.closeQuietly(inStream);
    }
}

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

@Bean
protected CommandLineRunner run(RestTemplate restTemplate) throws Exception {
    return args -> {

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

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

        File tmpDirectory = new File(tmpPath);
        tmpDirectory.mkdir();/*from  ww  w .  j  a  v a 2  s  .  c o m*/

        int maxBitRate = 256;

        for (Child song : songs) {

            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 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();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
        }
    };

}

From source file:org.robam.xutils.http.callback.FileDownloadHandler.java

/**
 * ?./*from   www  .j a  v  a 2 s  . c o  m*/
 *
 * @param entity
 * @param callBackHandler
 * @param target
 * @param isResume
 * @param responseFileName
 * @return ??.??.???, ??.
 * @throws java.io.IOException
 */
public File handleEntity(HttpEntity entity, RequestCallBackHandler callBackHandler, String target,
        boolean isResume, String responseFileName) throws IOException {
    if (entity == null || TextUtils.isEmpty(target)) {
        return null;
    }

    File targetFile = new File(target);

    //??
    if (!targetFile.exists()) {
        File dir = targetFile.getParentFile();
        //
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //?
        targetFile.createNewFile();
    }

    long currentFileSize = 0;
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;

    try {
        if (isResume) {
            currentFileSize = targetFile.length();
            // true
            fileOutputStream = new FileOutputStream(target, true);
        } else {
            fileOutputStream = new FileOutputStream(target);
        }

        // 
        long totalFileSize = entity.getContentLength() + currentFileSize;

        //TODO:?CallbackHandler????,?...
        if (callBackHandler != null && !callBackHandler.updateProgress(totalFileSize, currentFileSize, true)) {
            return targetFile;
        }

        // TODO:?entity.getContent??????????????
        inputStream = entity.getContent();
        BufferedInputStream bis = new BufferedInputStream(inputStream);

        byte[] tmp = new byte[4096];
        int len;
        while ((len = bis.read(tmp)) != -1) {
            fileOutputStream.write(tmp, 0, len);
            currentFileSize += len;
            if (callBackHandler != null) {
                if (!callBackHandler.updateProgress(totalFileSize, currentFileSize, false)) {
                    return targetFile;
                }
            }
        }
        fileOutputStream.flush();
        if (callBackHandler != null) {
            callBackHandler.updateProgress(totalFileSize, currentFileSize, true);
        }
    } finally {
        //
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }

    // ???
    if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) {
        File newFile = new File(targetFile.getParent(), responseFileName);
        //???,????.
        while (newFile.exists()) {
            newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName);
        }
        return targetFile.renameTo(newFile) ? newFile : targetFile;
    } else {
        return targetFile;
    }
}

From source file:eu.annocultor.tagger.server.controllers.SolrTaggerController.java

private List<String[]> readFile(String url) throws IOException {
    FileInputStream fStream = new FileInputStream(new File(url));
    StringBuffer sb = new StringBuffer();
    BufferedInputStream bin = new BufferedInputStream(fStream);
    byte[] contents = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = bin.read(contents)) != -1) {
        sb.append(new String(contents, 0, bytesRead));
    }/*w w  w.  j  av a 2s .  co m*/
    String toImport = StringUtils.substringBetween(sb.toString(), "Import\n", "Delete\n");
    List<String[]> collections = new ArrayList<String[]>();
    String[] collectionsToImport = StringUtils.split(toImport, "\n");
    collections.add(collectionsToImport);
    String toDelete = StringUtils.substringAfter(sb.toString(), "Delete\n");
    String[] collectionsToDelete = StringUtils.split(toDelete, "\n");
    collections.add(collectionsToDelete);
    return collections;
}

From source file:CharsetDetector.java

private Charset detectCharset(File f, Charset charset) {
    try {/*from w  ww  .  j  av  a2 s  . c  o m*/
        BufferedInputStream input = new BufferedInputStream(new FileInputStream(f));

        CharsetDecoder decoder = charset.newDecoder();
        decoder.reset();

        byte[] buffer = new byte[512];
        boolean identified = false;
        while ((input.read(buffer) != -1) && (!identified)) {
            identified = identify(buffer, decoder);
        }

        input.close();

        if (identified) {
            return charset;
        } else {
            return null;
        }

    } catch (Exception e) {
        return null;
    }
}

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

private static void add(File source, JarOutputStream target) throws IOException {
    BufferedInputStream in = null;
    try {// www. jav a2s.c o  m
        if (source.isDirectory()) {
            String name = source.getPath().replace("\\", "/");
            if (!name.isEmpty()) {
                if (!name.endsWith("/"))
                    name += "/";
                JarEntry entry = new JarEntry(name);
                entry.setTime(source.lastModified());
                target.putNextEntry(entry);
                target.closeEntry();
            }
            for (File nestedFile : source.listFiles())
                add(nestedFile, target);
            return;
        }

        JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
        entry.setTime(source.lastModified());
        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();
    } finally {
        if (in != null)
            in.close();
    }
}