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.tesshu.subsonic.client.sample4_music_andmovie.StreamDownloadAndPlayApplication.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);

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

    Optional<SearchResult2> result2 = search2.getOf("e", null, null, null, null, 1, null, null);

    result2.ifPresent(result -> {
        Optional<Child> maybeSong = result.getSongs().stream().findFirst();
        maybeSong.ifPresent(song -> {

            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 {
                            BufferedOutputStream fos = new BufferedOutputStream(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();
                        }

                        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);
                        MediaView view = new MediaView(player);
                        ((Group) scene.getRoot()).getChildren().add(view);
                        stage.setScene(scene);
                        stage.show();

                        player.play();

                    }, callback);

        });

    });
}

From source file:com.teasoft.teavote.util.Signature.java

/**
 * Signs a given sql backup digitally. The file to sign is modified by
 * prepending the public key to it. The resultant file is digitally signed.
 * The public key is removed and a caution message and the digital signature
 * is written at the top of the file.//from  ww w . ja v a 2 s. co  m
 *
 * In verifying the file, the caution message and digital signature must be
 * replaced with the public key
 *
 * @param pathToData
 * @throws FileNotFoundException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws InvalidKeySpecException
 */
public void signData(String pathToData) throws FileNotFoundException, IOException, NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException, SignatureException, InvalidKeySpecException {
    String pathToDuplicate = new ConfigLocation().getConfigPath() + File.separator + "duplicate.sql";
    try ( //Create a copy of the file
            FileInputStream originalFileIs = new FileInputStream(pathToData)) {
        File duplicateFile = new File(pathToDuplicate);
        try (FileOutputStream fos = new FileOutputStream(duplicateFile)) {
            fos.write(IOUtils.toByteArray(originalFileIs));
            //fos.flush();
            originalFileIs.close();
        }
    }

    byte[] buffer = new byte[1024];
    int nRead = 0;

    java.security.Signature dsa = java.security.Signature.getInstance("SHA1withDSA", "SUN");
    dsa.initSign(getPrivateKey());
    FileInputStream fis = new FileInputStream(pathToData);
    BufferedInputStream bufin = new BufferedInputStream(fis);
    int len;
    while ((len = bufin.read(buffer)) >= 0) {
        dsa.update(buffer, 0, len);
    }
    ;
    bufin.close();
    byte[] realSig = dsa.sign();

    //Create file starting with the signature
    String sigString = "-- " + Base64.encodeBase64String(realSig);
    String caution = "-- CAUTION: THIS FILE IS DIGITALLY SIGNED. DO NOT MODIFY IT. ANY CHANGE WILL RENDER IT UNRESTORABLE";

    FileOutputStream signedDataFw = new FileOutputStream(pathToData);
    signedDataFw.write("--\n".getBytes());
    signedDataFw.write((caution + "\n").getBytes());
    signedDataFw.write((sigString + "\n").getBytes());
    signedDataFw.write("--\n".getBytes());
    signedDataFw.write("\n".getBytes());
    //Write data to file.
    File duplicateFile = new File(pathToDuplicate);
    FileInputStream duplicateFileReader = new FileInputStream(duplicateFile);

    while ((nRead = duplicateFileReader.read(buffer)) != -1) {
        signedDataFw.write(buffer, 0, nRead);
    }
    //signedDataFw.flush();
    signedDataFw.close();
    duplicateFileReader.close();
    duplicateFile.delete();
}

From source file:cn.vlabs.clb.server.web.FileInfo.java

public String getSHA256() throws IOException {
    File file = this.getFile();
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
    byte[] temp = new byte[1024];
    int size = 0;
    while ((size = in.read(temp)) != -1) {
        out.write(temp, 0, size);//w w  w  .jav  a 2  s  . c o m
    }
    in.close();

    byte[] content = out.toByteArray();

    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(content);
        String output = Hex.encodeHexString(hash);
        System.out.println(output);
        return output;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return "";
}

From source file:crush.CrushUtil.java

protected void textCrush(FileSystem fs, FileStatus[] status) throws IOException, CrushException {
    FSDataOutputStream out = fs.create(outPath);
    BufferedOutputStream bw = new java.io.BufferedOutputStream(out);
    for (FileStatus stat : status) {
        BufferedInputStream br = new BufferedInputStream(fs.open(stat.getPath()));
        byte[] buffer = new byte[2048];
        int read = -1;
        while ((read = br.read(buffer)) != -1) {
            bw.write(buffer, 0, read);//  w  w  w .  ja v  a2  s  . com
        }
        br.close();
    }
    bw.close();
}

From source file:com.android.idtt.http.client.ResponseStream.java

public void readFile(String savePath) throws IOException {
    if (_directResult != null)
        return;// w  w  w  . ja v  a2  s  .c  o m
    if (baseStream == null)
        return;
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(savePath);
        BufferedInputStream ins = new BufferedInputStream(baseStream);
        byte[] buffer = new byte[4096];
        int len = 0;
        while ((len = ins.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(baseStream);
    }
}

From source file:com.lidroid.xutils.http.client.ResponseStream.java

public void readFile(String savePath) throws IOException {
    if (_directResult != null)
        return;/*www  .j a v a  2 s .c  o  m*/
    if (baseStream == null)
        return;
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(savePath);
        BufferedInputStream ins = new BufferedInputStream(baseStream);
        byte[] buffer = new byte[4096];
        int len = 0;
        while ((len = ins.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(baseStream);
    }
}

From source file:ezbake.frack.submitter.util.JarUtil.java

private static void add(File source, final String prefix, JarOutputStream target) throws IOException {
    BufferedInputStream in = null;
    log.debug("Adding file {} to jar", source.getName());
    try {//from   w w  w  . j av a2s.c om
        String entryPath = source.getPath().replace("\\", "/").replace(prefix, "");
        if (entryPath.startsWith("/")) {
            entryPath = entryPath.substring(1);
        }
        if (source.isDirectory()) {
            if (!entryPath.isEmpty()) {
                if (!entryPath.endsWith("/")) {
                    entryPath += "/";
                }
                JarEntry entry = new JarEntry(entryPath);
                entry.setTime(source.lastModified());
                target.putNextEntry(entry);
                target.closeEntry();
            }
            for (File nestedFile : source.listFiles()) {
                add(nestedFile, prefix, target);
            }
        } else {
            JarEntry entry = new JarEntry(entryPath);
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            in = new BufferedInputStream(new FileInputStream(source));

            byte[] buffer = new byte[BUFFER_SIZE];
            int len;
            while ((len = in.read(buffer)) > 0) {
                target.write(buffer, 0, len);
            }
            target.closeEntry();
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:oz.hadoop.yarn.api.utils.JarUtils.java

/**
 *
 * @param source/*from ww  w.j a  va 2  s  .  com*/
 * @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 (StringUtils.hasText(message)) {
                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:net.dfs.remote.fileretrieve.impl.RetrievalManagerImpl.java

/**
 * Read the File from the local disk and send it to the Space.
 * Connect to the remote Space via {@link FileSpaceCreator}. Read the bites in 
 * the File into a InputStream and set the properties of the created File model. 
 * <p>/*w w  w .  j a  v  a2  s . c o m*/
 * File model properties are FileName, the size of the file in bites and the
 * actual bites read in the File. Finally send the wrapped File to the Space
 * via {@link FileSenderSupport}
 * <p>
 * IOException will be thrown on a failure.
 * {@inheritDoc}
 * @throws IOException 
 */
public FileRetrievalModel retrieveFile(String fileName) throws IOException {

    BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(new File(path + fileName)));

    byte[] buffer = new byte[inputStream.available()];
    Integer bytesRead = 0;

    FileRetrievalModel fileModel = new FileRetrievalModel();

    while ((bytesRead = inputStream.read(buffer)) != -1) {
        fileModel.fileName = fileName;
        fileModel.bytes = buffer;
        fileModel.bytesRead = bytesRead;
    }

    log.info("The File " + fileModel.fileName + " with bytes " + fileModel.bytesRead
            + " Sending back to the Server");
    return fileModel;
}

From source file:com.honnix.yaacs.adapter.http.ui.ACHttpClientCli.java

private void save(String filePath, InputStream is) throws IOException {
    File file = new File(filePath);
    File directory = new File(file.getParent());

    if (!directory.exists()) {
        directory.mkdirs();/*from   ww  w . ja  va  2s . c  om*/
    }

    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
    BufferedInputStream bis = new BufferedInputStream(is);
    byte[] buffer = new byte[255];
    int length = -1;

    while ((length = bis.read(buffer)) != -1) {
        bos.write(buffer, 0, length);
    }

    bos.flush();
    StreamUtil.closeStream(bos);
    StreamUtil.closeStream(bis);
}