Example usage for java.io BufferedOutputStream write

List of usage examples for java.io BufferedOutputStream write

Introduction

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

Prototype

@Override
public synchronized void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this buffered output stream.

Usage

From source file:it.readbeyond.minstrel.librarian.FormatHandlerAbstractZIP.java

protected void extractCover(File f, Format format, String publicationID) {
    String destinationName = publicationID + "." + format.getName() + ".png";
    String entryName = format.getMetadatum("internalPathCover");

    if ((entryName == null) || (entryName.equals(""))) {
        format.addMetadatum("relativePathThumbnail", "");
        return;/*from   w w w.  ja v  a  2  s  .c o  m*/
    }

    try {
        ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ);
        ZipEntry entry = zipFile.getEntry(entryName);
        File destFile = new File(this.thumbnailDirectoryPath, "orig-" + destinationName);
        String destinationPath = destFile.getAbsolutePath();

        BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
        int numberOfBytesRead;
        byte data[] = new byte[BUFFER_SIZE];

        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);

        while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
            dest.write(data, 0, numberOfBytesRead);
        }
        dest.flush();
        dest.close();
        is.close();
        fos.close();

        // create thumbnail
        FileInputStream fis = new FileInputStream(destinationPath);
        Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, this.thumbnailWidth, this.thumbnailHeight, false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imageData = baos.toByteArray();

        // write thumbnail to file 
        File destFile2 = new File(this.thumbnailDirectoryPath, destinationName);
        String destinationPath2 = destFile2.getAbsolutePath();
        FileOutputStream fos2 = new FileOutputStream(destFile2);
        fos2.write(imageData, 0, imageData.length);
        fos2.flush();
        fos2.close();
        baos.close();

        // close ZIP
        zipFile.close();

        // delete original cover
        destFile.delete();

        // set relativePathThumbnail
        format.addMetadatum("relativePathThumbnail", destinationName);

    } catch (Exception e) {
        // nop 
    }
}

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   w ww  . j av  a 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);
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.util.RepositoryFileObject.java

@Override
protected InputStream doGetInputStream() throws Exception {

    if (fileResource == null) {
        throw new JSException("no resource. URI: " + getName());
    }/* w  ww. j  a  va 2  s .  c om*/

    InputStream data = resourceData != null ? resourceData.getDataStream() : fileResource.getDataStream();

    // TODO: Should this be cached?

    InputStream in = null;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
    try {
        in = new BufferedInputStream(data);
        byte[] buf = new byte[10000];
        int numRead = 0;
        while ((numRead = in.read(buf)) != -1) {
            bufferedOut.write(buf, 0, numRead);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        bufferedOut.flush();
    }

    return new BufferedInputStream(new ByteArrayInputStream(out.toByteArray()));
}

From source file:SimpleFTP.java

/**
 * Sends a file to be stored on the FTP server. Returns true if the file
 * transfer was successful. The file is sent in passive mode to avoid NAT or
 * firewall problems at the client end./*from w ww  .  j a v  a  2s . c  o  m*/
 */
public synchronized boolean stor(InputStream inputStream, String filename) throws IOException {

    BufferedInputStream input = new BufferedInputStream(inputStream);

    sendLine("PASV");
    String response = readLine();
    if (!response.startsWith("227 ")) {
        throw new IOException("SimpleFTP could not request passive mode: " + response);
    }

    String ip = null;
    int port = -1;
    int opening = response.indexOf('(');
    int closing = response.indexOf(')', opening + 1);
    if (closing > 0) {
        String dataLink = response.substring(opening + 1, closing);
        StringTokenizer tokenizer = new StringTokenizer(dataLink, ",");
        try {
            ip = tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken() + "."
                    + tokenizer.nextToken();
            port = Integer.parseInt(tokenizer.nextToken()) * 256 + Integer.parseInt(tokenizer.nextToken());
        } catch (Exception e) {
            throw new IOException("SimpleFTP received bad data link information: " + response);
        }
    }

    sendLine("STOR " + filename);

    Socket dataSocket = new Socket(ip, port);

    response = readLine();
    if (!response.startsWith("125 ")) {
        //if (!response.startsWith("150 ")) {
        throw new IOException("SimpleFTP was not allowed to send the file: " + response);
    }

    BufferedOutputStream output = new BufferedOutputStream(dataSocket.getOutputStream());
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    while ((bytesRead = input.read(buffer)) != -1) {
        output.write(buffer, 0, bytesRead);
    }
    output.flush();
    output.close();
    input.close();

    response = readLine();
    return response.startsWith("226 ");
}

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);
        }/*from  www. j  a  va  2  s  . c o m*/
        br.close();
    }
    bw.close();
}

From source file:com.gsr.myschool.server.reporting.excel.ExcelController.java

@RequestMapping(method = RequestMethod.GET, value = "/excel", produces = "application/vnd.ms-excel")
@ResponseStatus(HttpStatus.OK)/*  w  w w . j  av  a 2  s . co  m*/
public void generateExcel(@RequestParam String fileName, HttpServletRequest request,
        HttpServletResponse response) {
    try {
        final int buffersize = 1024;
        final byte[] buffer = new byte[buffersize];

        response.addHeader("Content-Disposition", "attachment; filename=recherche.xls");

        File file = new File(
                request.getSession().getServletContext().getRealPath("/") + TMP_FOLDER_PATH + fileName);
        InputStream inputStream = new FileInputStream(file);
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

        int available = 0;
        while ((available = inputStream.read(buffer)) >= 0) {
            outputStream.write(buffer, 0, available);
        }

        inputStream.close();

        outputStream.flush();
        outputStream.close();

        file.delete();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gsr.myschool.server.reporting.excel.ExcelController.java

@RequestMapping(method = RequestMethod.GET, value = "/dossierconvoques", produces = "application/vnd.ms-excel")
@ResponseStatus(HttpStatus.OK)//from  w  w  w .j  a  v  a2 s .c  om
public void generateDossierConvoquesExcel(@RequestParam String fileName, HttpServletRequest request,
        HttpServletResponse response) {
    try {
        final int buffersize = 1024;
        final byte[] buffer = new byte[buffersize];

        response.addHeader("Content-Disposition", "attachment; filename=dossierconvoques.xls");

        File file = new File(
                request.getSession().getServletContext().getRealPath("/") + TMP_FOLDER_PATH + fileName);
        InputStream inputStream = new FileInputStream(file);
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

        int available = 0;
        while ((available = inputStream.read(buffer)) >= 0) {
            outputStream.write(buffer, 0, available);
        }

        inputStream.close();

        outputStream.flush();
        outputStream.close();

        file.delete();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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();/*ww w  .  ja  v  a  2  s  . co 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:it.readbeyond.minstrel.unzipper.Unzipper.java

private String unzip(String inputZip, String destinationDirectory, String mode, JSONObject parameters)
        throws IOException, JSONException {

    // store the zip entries to decompress
    List<String> list = new ArrayList<String>();

    // store the zip entries actually decompressed
    List<String> decompressed = new ArrayList<String>();

    // open input zip file
    File sourceZipFile = new File(inputZip);
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // open destination directory, creating it if needed    
    File unzipDestinationDirectory = new File(destinationDirectory);
    unzipDestinationDirectory.mkdirs();/*from  w w w . ja  v  a 2s. c o m*/

    // extract all files
    if (mode.equals(ARGUMENT_MODE_ALL)) {
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            list.add(zipFileEntries.nextElement().getName());
        }
    }

    // extract all files except audio and video
    // (determined by file extension)
    if (mode.equals(ARGUMENT_MODE_ALL_NON_MEDIA)) {
        String[] excludeExtensions = JSONArrayToStringArray(
                parameters.optJSONArray(ARGUMENT_ARGS_EXCLUDE_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            if (!isFile(lower, excludeExtensions)) {
                list.add(name);
            }
        }
    }

    // extract all small files
    // maximum size is passed in args parameter
    // or, if not passed, defaults to const DEFAULT_MAXIMUM_SIZE_FILE
    if (mode.equals(ARGUMENT_MODE_ALL_SMALL)) {
        long maximum_size = parameters.optLong(ARGUMENT_ARGS_MAXIMUM_FILE_SIZE, DEFAULT_MAXIMUM_SIZE_FILE);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            if (ze.getSize() <= maximum_size) {
                list.add(ze.getName());
            }
        }
    }

    // extract only the requested files
    if (mode.equals(ARGUMENT_MODE_SELECTED)) {
        String[] entries = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_ENTRIES));
        for (String entry : entries) {
            ZipEntry ze = zipFile.getEntry(entry);
            if (ze != null) {
                list.add(entry);
            }
        }
    }

    // extract all "structural" files
    if (mode.equals(ARGUMENT_MODE_ALL_STRUCTURE)) {
        String[] extensions = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            boolean extract = isFile(lower, extensions);
            if (extract) {
                list.add(name);
            }
        }
    }

    // NOTE list contains only valid zip entries
    // perform unzip
    for (String currentEntry : list) {
        ZipEntry entry = zipFile.getEntry(currentEntry);
        File destFile = new File(unzipDestinationDirectory, currentEntry);

        File destinationParent = destFile.getParentFile();
        destinationParent.mkdirs();

        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            int numberOfBytesRead;
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);
            while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
                dest.write(data, 0, numberOfBytesRead);
            }
            dest.flush();
            dest.close();
            is.close();
            fos.close();
            decompressed.add(currentEntry);
        }
    }

    zipFile.close();
    return stringify(decompressed);
}

From source file:com.phonegap.plugin.files.ExtractZipFilePlugin.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext cbc) {
    PluginResult.Status status = PluginResult.Status.OK;
    try {/*from   w w  w .  j a  v  a2  s .c o m*/
        String filename = args.getString(0);
        URL url;
        try {
            url = new URL(filename);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        File file = new File(url.getFile());
        String[] dirToSplit = url.getFile().split(File.separator);
        String dirToInsert = "";
        for (int i = 0; i < dirToSplit.length - 1; i++) {
            dirToInsert += dirToSplit[i] + File.separator;
        }

        ZipEntry entry;
        ZipFile zipfile;
        try {
            zipfile = new ZipFile(file);
            Enumeration e = zipfile.entries();
            while (e.hasMoreElements()) {
                entry = (ZipEntry) e.nextElement();
                BufferedInputStream is = null;
                try {
                    is = new BufferedInputStream(zipfile.getInputStream(entry));
                    int count;
                    byte data[] = new byte[102222];
                    String fileName = dirToInsert + entry.getName();
                    File outFile = new File(fileName);
                    if (entry.isDirectory()) {
                        if (!outFile.exists() && !outFile.mkdirs()) {
                            Log.v("info", "Unable to create directories: " + outFile.getAbsolutePath());
                            cbc.sendPluginResult(new PluginResult(IO_EXCEPTION));
                            return false;
                        }
                    } else {
                        File parent = outFile.getParentFile();
                        if (parent.mkdirs()) {
                            Log.v("info", "created directory leading to file");
                        }
                        FileOutputStream fos = null;
                        BufferedOutputStream dest = null;
                        try {
                            fos = new FileOutputStream(outFile);
                            dest = new BufferedOutputStream(fos, 102222);
                            while ((count = is.read(data, 0, 102222)) != -1) {
                                dest.write(data, 0, count);
                            }
                        } finally {
                            if (dest != null) {
                                dest.flush();
                                dest.close();
                            }
                            if (fos != null) {
                                fos.close();
                            }
                        }
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            }
        } catch (ZipException e1) {
            Log.v("error", e1.getMessage(), e1);
            cbc.sendPluginResult(new PluginResult(MALFORMED_URL_EXCEPTION));
            return false;
        } catch (IOException e1) {
            Log.v("error", e1.getMessage(), e1);
            cbc.sendPluginResult(new PluginResult(IO_EXCEPTION));
            return false;
        }

    } catch (JSONException e) {
        cbc.sendPluginResult(new PluginResult(JSON_EXCEPTION));
        return false;
    }
    cbc.sendPluginResult(new PluginResult(status));
    return true;
}