Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

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

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:fr.shywim.antoinedaniel.sync.AppState.java

/**
 * Save the AppState to a file.//from w w w  .j  a  va 2  s. c  om
 *
 * @param context a context.
 */
public void save(Context context) {
    if (changed) {
        File privDir = context.getFilesDir();
        File appState = new File(privDir, FILE_NAME);

        try {
            byte[] bytes = getAsByteArray();
            if (appState.exists() || (!appState.exists() && appState.createNewFile())) {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(appState));
                bos.write(bytes);
                bos.flush();
                bos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.honnix.cheater.bundle.CheaterActivator.java

private void setTrustStore(BundleContext context) throws IOException {
    InputStream is = context.getBundle().getEntry("/etc/jssecacerts").openStream();
    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(TEMP_TRUST_STORE));

    byte[] buffer = new byte[255];
    int length;//from   w w  w .j av  a 2 s  . c  om

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

    os.flush();
    os.close();
    is.close();

    System.setProperty(CheaterConstant.TRUST_STORE_KEY, TEMP_TRUST_STORE);
}

From source file:com.noshufou.android.su.util.Util.java

public static ArrayList<String> run(String shell, String[] commands) {
    ArrayList<String> output = new ArrayList<String>();

    try {//from ww w.  j  a v a  2 s.co  m
        Process process = Runtime.getRuntime().exec(shell);

        BufferedOutputStream shellInput = new BufferedOutputStream(process.getOutputStream());
        BufferedReader shellOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));

        for (String command : commands) {
            Log.i(TAG, "command: " + command);
            shellInput.write((command + " 2>&1\n").getBytes());
        }

        shellInput.write("exit\n".getBytes());
        shellInput.flush();

        String line;
        while ((line = shellOutput.readLine()) != null) {
            Log.d(TAG, "command output: " + line);
            output.add(line);
        }

        process.waitFor();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return output;
}

From source file:com.zenika.dorm.maven.test.grinder.GrinderGenerateJson.java

/**
 * @param file         to generate checksum
 * @param fileChecksum to put the generated checksum
 *///w  w  w .  j  av  a  2  s. c o m
private static void generateChecksum(File file, File fileChecksum, String checksumType) {
    FileOutputStream outputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    FileInputStream inputStream = null;
    BufferedInputStream bufferedInputStream = null;
    try {
        MessageDigest digest = MessageDigest.getInstance(checksumType);

        outputStream = new FileOutputStream(fileChecksum);
        bufferedOutputStream = new BufferedOutputStream(outputStream);

        inputStream = new FileInputStream(file);
        bufferedInputStream = new BufferedInputStream(inputStream);
        byte[] dataBytes = new byte[1024];
        int nread = 0;

        while ((nread = bufferedInputStream.read(dataBytes)) != -1) {
            digest.update(dataBytes, 0, nread);
        }

        byte[] byteDigested = digest.digest();

        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < byteDigested.length; i++) {
            sb.append(Integer.toString((byteDigested[i] & 0xff) + 0x100, 16).substring(1));
        }

        bufferedOutputStream.write(sb.toString().getBytes());
        bufferedOutputStream.flush();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to digest this file: " + file, e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Unable to digest this file: " + file, e);
    } catch (IOException e) {
        throw new RuntimeException("Unable to digest this file: " + file, e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Unable to digest this file: " + file, e);
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Unable to digest this file: " + file, e);
            }
        }
        if (bufferedInputStream != null) {
            try {
                bufferedInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Unable to digest this file: " + file, e);
            }
        }
        if (bufferedOutputStream != null) {
            try {
                bufferedOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Unable to digest this file: " + file, e);
            }
        }
    }
}

From source file:com.rapleaf.hank.storage.HdfsPartitionRemoteFileOps.java

@Override
public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException {
    Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath));
    File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName());
    LOG.info("Copying remote file " + source + " to local file " + destination);
    InputStream inputStream = getInputStream(remoteSourceRelativePath);
    FileOutputStream fileOutputStream = new FileOutputStream(destination);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
    // Use copyLarge (over 2GB)
    try {/*from   w w  w. j  a v a 2 s. com*/
        IOUtils.copyLarge(inputStream, bufferedOutputStream);
        bufferedOutputStream.flush();
        fileOutputStream.flush();
    } finally {
        inputStream.close();
        bufferedOutputStream.close();
        fileOutputStream.close();
    }
}

From source file:com.seongil.avatarpicker.AbstractAvatarPicker.java

private void saveAvatarImgToFileSystemStorage(@NonNull Bitmap bitmap) {
    final File tempFile = new File(mUri.getPath());
    final File file = new File(getDirectoryFile(), tempFile.getName());
    try {/*from ww  w. j  ava  2 s .c  o m*/
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
    } catch (IOException e) {
        showToastMsg(e.getMessage());
    }
}

From source file:com.gsr.myschool.server.reporting.bilan.SummaryController.java

@RequestMapping(method = RequestMethod.GET, produces = "application/vnd.ms-excel")
@ResponseStatus(HttpStatus.OK)//from   ww w  .  j  a v a2s . co  m
public void generateBilan(@RequestParam(required = false) String annee, HttpServletResponse response) {
    ValueList anneeScolaire;

    try {
        anneeScolaire = valueListRepos.findByValueAndValueTypeCode(annee, ValueTypeCode.SCHOOL_YEAR);
        if (anneeScolaire == null) {
            anneeScolaire = getCurrentScholarYear();
        }
    } catch (Exception e) {
        return;
    }

    List<SummaryExcelDTO> dto = getReportSummary(anneeScolaire);

    try {
        response.addHeader("Content-Disposition", "attachment; filename=summary.xls");

        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        xlsExportService.saveSpreadsheetRecords(SummaryExcelDTO.class, dto, outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sf.sahi.util.Utils.java

public static byte[] getBytes(final InputStream in, final int contentLength) throws IOException {
    BufferedInputStream bin = new BufferedInputStream(in, BUFFER_SIZE);

    if (contentLength != -1) {
        int totalBytesRead = 0;
        byte[] buffer = new byte[contentLength];
        while (totalBytesRead < contentLength) {
            int bytesRead = -1;
            try {
                bytesRead = bin.read(buffer, totalBytesRead, contentLength - totalBytesRead);
            } catch (EOFException e) {
            }// ww w. ja  v  a  2 s  .  c  om
            if (bytesRead == -1) {
                break;
            }
            totalBytesRead += bytesRead;
        }
        return buffer;
    } else {
        ByteArrayOutputStream byteArOut = new ByteArrayOutputStream();
        BufferedOutputStream bout = new BufferedOutputStream(byteArOut);
        try {
            int totalBytesRead = 0;
            byte[] buffer = new byte[BUFFER_SIZE];

            while (true) {
                int bytesRead = -1;
                try {
                    bytesRead = bin.read(buffer);
                } catch (EOFException e) {
                }
                if (bytesRead == -1) {
                    break;
                }
                bout.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;
            }
        } catch (SocketTimeoutException ste) {
            ste.printStackTrace();
        }
        bout.flush();
        bout.close();
        return byteArOut.toByteArray();
    }
}

From source file:org.jaqpot.core.service.resource.ReportResource.java

@GET
@Path("/{id}/pdf")
@Produces("application/json; charset=UTF-8")
@ApiOperation(value = "Creates PDF from report")
public Response createPDF(@ApiParam(value = "Authorization token") @HeaderParam("subjectid") String subjectId,
        @PathParam("id") String id) {
    Report report = reportHandler.find(id);
    if (report == null) {
        throw new NotFoundException();
    }//from  w ww  . ja va2s .c  om

    StreamingOutput out = (OutputStream output) -> {
        BufferedOutputStream buffer = new BufferedOutputStream(output);
        try {
            reportService.report2PDF(report, output);
        } finally {
            buffer.flush();
        }
    };
    return Response.ok(out)
            .header("Content-Disposition", "attachment; filename=" + "report-" + report.getId() + ".pdf")
            .build();
}

From source file:org.broadleafcommerce.admin.util.controllers.FileUploadController.java

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws ServletException, IOException {

    // cast the bean
    FileUploadBean bean = (FileUploadBean) command;

    // let's see if there's content there
    MultipartFile file = bean.getFile();
    if (file == null) {
        // hmm, that's strange, the user did not upload anything
    }/*  w w w. j  a v a  2s  .co m*/

    try {
        String basepath = request.getPathTranslated().substring(0,
                request.getPathTranslated().indexOf(File.separator + "upload"));
        String absoluteFilename = basepath + File.separator + bean.getDirectory() + File.separator
                + file.getOriginalFilename();
        FileSystemResource fileResource = new FileSystemResource(absoluteFilename);

        checkDirectory(basepath + File.separator + bean.getDirectory());

        backupExistingFile(fileResource, basepath + bean.getDirectory());

        FileOutputStream fout = new FileOutputStream(new FileSystemResource(
                basepath + File.separator + bean.getDirectory() + File.separator + file.getOriginalFilename())
                        .getFile());
        BufferedOutputStream bout = new BufferedOutputStream(fout);
        BufferedInputStream bin = new BufferedInputStream(file.getInputStream());
        int x;
        while ((x = bin.read()) != -1) {
            bout.write(x);
        }
        bout.flush();
        bout.close();
        bin.close();
        return super.onSubmit(request, response, command, errors);
    } catch (Exception e) {
        //Exception occured;
        e.printStackTrace();
        throw new RuntimeException(e);
        // return null;                
    }
}