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(int b) throws IOException 

Source Link

Document

Writes the specified byte to this buffered output stream.

Usage

From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java

public static void saveFile(String foldername, String filename, InputStream input) throws IOException {

    // LogWriter log = LogWriter.getInstance();

    if (filename == null) {
        filename = File.createTempFile("xx", ".out").getName(); //$NON-NLS-1$ //$NON-NLS-2$
    }//from  ww  w .  java  2  s .  co  m
    // Do no overwrite existing file
    File file = new File(foldername, filename);
    for (int i = 0; file.exists(); i++) {
        file = new File(foldername, filename + i);
    }
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    BufferedInputStream bis = new BufferedInputStream(input);
    int aByte;
    while ((aByte = bis.read()) != -1) {
        bos.write(aByte);
    }

    bos.flush();
    bos.close();
    bis.close();
}

From source file:de.nrw.hbz.deepzoomer.fileUtil.FileUtil.java

/**
 * <p><em>Title: Create a temporary File from a file identified by URL</em></p>
 * <p>Description: Method creates a temporary file from a remote file addressed 
 * an by URL representing the orginal PDF, that should be converted</p>
 * //from  w  ww  .j  a v a  2  s.  c  o  m
 * @param fileName
 * @param url
 * @return 
 */
public static String saveUrlToFile(String fileName, String url) {
    File inputFile = new File(Configuration.getTempDirPath() + "/" + fileName);
    log.debug(inputFile.getAbsolutePath());
    InputStream is = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;

    log.info(url);
    try {
        URL inputDocument = new URL(url);
        is = inputDocument.openStream();
        bis = new BufferedInputStream(is);

        fos = new FileOutputStream(inputFile);
        bos = new BufferedOutputStream(fos);
        int i = -1;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
    }
    return inputFile.getName();
}

From source file:com.wabacus.system.dataimport.DataImportItem.java

public static void backupOrDeleteDataFile(File fileObj) {
    try {//from www  . ja va 2 s . c o m
        if (fileObj == null || !fileObj.exists()) {
            return;
        }
        String backuppath = Config.getInstance().getSystemConfigValue("dataimport-backuppath", "");
        if (backuppath.equals("")) {
            log.debug("?" + fileObj.getAbsolutePath());
        } else {//?
            String filename = fileObj.getName();
            int idxdot = filename.lastIndexOf(".");
            if (idxdot > 0) {
                filename = filename.substring(0, idxdot) + "_"
                        + Tools.getStrDatetime("yyyyMMddHHmmss", new Date()) + filename.substring(idxdot);
            } else {
                filename = filename + "_" + Tools.getStrDatetime("yyyyMMddHHmmss", new Date());
            }
            File destFile = new File(
                    FilePathAssistant.getInstance().standardFilePath(backuppath + File.separator + filename));
            log.debug("?" + fileObj.getAbsolutePath() + "" + backuppath
                    + "");
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                bis = new BufferedInputStream(new FileInputStream(fileObj));
                bos = new BufferedOutputStream(new FileOutputStream(destFile));
                byte[] btmp = new byte[1024];
                while (bis.read(btmp) != -1) {
                    bos.write(btmp);
                }
            } catch (Exception e) {
                log.error("?" + fileObj.getAbsolutePath() + "", e);
            } finally {
                try {
                    if (bis != null)
                        bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (bos != null)
                        bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        fileObj.delete();
    } catch (Exception e) {
        log.error("?" + fileObj.getAbsolutePath() + "", e);
    }
}

From source file:de.uzk.hki.da.sb.restfulService.FileUtil.java

/**
 * <p><em>Title: Create a temporary File from a file identified by URL</em></p>
 * <p>Description: Method creates a temporary file from a remote file addressed 
 * an by URL representing the orginal PDF, that should be converted</p>
 * /*ww  w .ja va 2  s  . c  o  m*/
 * @param fileName
 * @param url
 * @return 
 */
public static String saveUrlToFile(String fileName, String url) {

    String path = fileName.substring(0, fileName.lastIndexOf("/"));
    File dir = new File(Configuration.getTempDirPath() + "/" + path);
    dir.mkdirs();

    File inputFile = new File(Configuration.getTempDirPath() + "/" + fileName);
    InputStream is = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;

    log.info(url);
    try {
        URL inputDocument = new URL(url);
        is = inputDocument.openStream();
        bis = new BufferedInputStream(is);

        fos = new FileOutputStream(inputFile);
        bos = new BufferedOutputStream(fos);
        int i = -1;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
    }

    return inputFile.getAbsolutePath();
}

From source file:de.petermoesenthin.alarming.util.FileUtil.java

/**
 * Copies a file to the Alarming directory in the external storage
 *
 * @param context Application context/*from  w w w .  ja v a 2s.c o  m*/
 * @param uri     Uri of file to copy
 */
public static void saveFileToExtAppStorage(final Context context, final Uri uri,
        final OnCopyFinishedListener op) {
    final File applicationDirectory = getApplicationDirectory();
    if (!applicationDirectory.exists()) {
        applicationDirectory.mkdirs();
    }
    File noMedia = new File(applicationDirectory.getPath() + File.separatorChar + ".nomedia");
    if (!noMedia.exists()) {
        try {
            noMedia.createNewFile();
            Log.e(DEBUG_TAG, "Created .nomedia file in: " + noMedia.getAbsolutePath());
        } catch (IOException e) {
            Log.e(DEBUG_TAG, "Unable to create .nomedia file", e);
        }
    }

    String fileName = getFilenameFromUriNoSpace(uri);
    final File destinationFile = new File(applicationDirectory.getPath() + File.separatorChar + fileName);

    Log.d(DEBUG_TAG, "Source file name: " + fileName);
    Log.d(DEBUG_TAG, "Source file uri: " + uri.toString());
    Log.d(DEBUG_TAG, "Destination file: " + destinationFile.getPath());

    Thread copyThread = new Thread(new Runnable() {
        @Override
        public void run() {
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            if (isExternalStorageWritable()) {
                try {
                    InputStream uriStream = context.getContentResolver().openInputStream(uri);
                    bis = new BufferedInputStream(uriStream);
                    bos = new BufferedOutputStream(new FileOutputStream(destinationFile.getPath(), false));
                    byte[] buf = new byte[1024];
                    while (bis.read(buf) != -1) {
                        bos.write(buf);
                    }
                } catch (IOException e) {
                    Log.e(DEBUG_TAG, "Unable to copy file from URI", e);

                } finally {
                    try {
                        if (bis != null)
                            bis.close();
                        if (bos != null)
                            bos.close();
                    } catch (IOException e) {
                        Log.e(DEBUG_TAG, "Unable to close buffers", e);
                    }
                }
            }
            if (op != null) {
                op.onOperationFinished();
            }
        }
    });
    copyThread.start();
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

/**
 * Saves attachment/*from w  ww .ja  v a 2 s  . c om*/
 */
public static File saveFile(String filename, InputStream input) throws IOException {
    // in case there is no filename, create temporary file and use its
    // filename instead
    String tempDir = HandleHome.getTrackplus_Home() + File.separator + HandleHome.DATA_DIR + File.separator
            + "temp";
    File dirTem = new File(tempDir);
    if (!dirTem.exists()) {
        dirTem.mkdirs();
    }
    File file;
    if (filename == null) {
        file = File.createTempFile("xxxxxx", ".out", dirTem);
    } else {
        // Existing files will not be overwritten
        file = new File(dirTem, filename);
    }

    int i = 0;
    while (file.exists()) {
        // Extend filename by number so it is unique
        file = new File(dirTem, i + filename);
        i++;
    }

    // BufferedOutputStream for writing into the file
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

    // BufferedInputStream for reading the parts
    BufferedInputStream bis = new BufferedInputStream(input);

    // read data and write to output stream
    int aByte;
    while ((aByte = bis.read()) != -1) {
        bos.write(aByte);
    }

    // release resources
    bos.flush();
    bos.close();
    bis.close();
    return file;
}

From source file:com.andrew.apollo.cache.ImageFetcher.java

/**
 * Download a {@link Bitmap} from a URL, write it to a disk and return the
 * File pointer. This implementation uses a simple disk cache.
 *
 * @param context The context to use//  w  w  w  .  j av a2s . c  om
 * @param urlString The URL to fetch
 * @return A {@link File} pointing to the fetched bitmap
 */
public static final File downloadBitmapToFile(final Context context, final String urlString,
        final String uniqueName) {
    final File cacheDir = ImageCache.getDiskCacheDir(context, uniqueName);

    if (!cacheDir.exists()) {
        cacheDir.mkdir();
    }

    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;

    try {
        final File tempFile = File.createTempFile("bitmap", null, cacheDir); //$NON-NLS-1$

        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        final InputStream in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
        out = new BufferedOutputStream(new FileOutputStream(tempFile), IO_BUFFER_SIZE_BYTES);

        int oneByte;
        while ((oneByte = in.read()) != -1) {
            out.write(oneByte);
        }
        return tempFile;
    } catch (final IOException ignored) {
        ignored.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException ignored) {
            }
        }
    }
    return null;
}

From source file:dictinsight.utils.io.HttpUtils.java

/**
 * https??post//from   w w w  .j  a v  a  2 s . com
 * @param url
 * @param param
 * @return post?
 */
public static String httpsPostData(String url, String param) {
    class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    BufferedOutputStream brOutStream = null;
    BufferedReader reader = null;

    try {
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        HttpsURLConnection connection = (HttpsURLConnection) (new URL(url)).openConnection();
        connection.setSSLSocketFactory(context.getSocketFactory());
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Proxy-Connection", "Keep-Alive");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(1000 * 15);

        brOutStream = new BufferedOutputStream(connection.getOutputStream());
        brOutStream.write(param.getBytes());
        brOutStream.flush();

        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String responseContent = "";
        String line = reader.readLine();
        while (line != null) {
            responseContent += line;
            line = reader.readLine();
        }

        return responseContent;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (brOutStream != null)
                brOutStream.close();
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.vmware.photon.controller.deployer.helpers.TestHelper.java

public static File createSourceFile(String sourceFileName, File sourceDirectory) throws IOException {
    sourceDirectory.mkdirs();// ww  w .j a v  a  2  s  . c  om

    if (sourceFileName == null) {
        sourceFileName = "esxcloud-" + UUID.randomUUID().toString() + ".vib";
    }

    File sourceFile = new File(sourceDirectory, sourceFileName);
    sourceFile.createNewFile();
    OutputStream outputStream = new FileOutputStream(sourceFile);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);

    Random random = new Random();
    byte[] randomBytes = new byte[1024];
    for (int i = 0; i < 10 * 1024; i++) {
        random.nextBytes(randomBytes);
        bufferedOutputStream.write(randomBytes);
    }

    bufferedOutputStream.close();
    outputStream.close();
    return sourceFile;
}

From source file:com.web.controller.ToolController.java

@ResponseBody
@RequestMapping(value = "/tool/verifyapk", method = RequestMethod.POST)
public String verifyApk(@RequestParam("apkfile") MultipartFile file) {

    //keytool -list -printcert -jarfile d:\weixin653android980.apk
    //keytool -printcert -file D:\testapp\META-INF\CERT.RSA
    //System.out.println("12345");
    try {/* ww  w.  ja v a2 s. c om*/
        OutputStream stream = new FileOutputStream(new File(file.getOriginalFilename()));
        BufferedOutputStream outputStream = new BufferedOutputStream(stream);
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();

        Runtime runtime = Runtime.getRuntime();
        String ccString = "keytool -list -printcert -jarfile C:\\Users\\Administrator\\Desktop\\zju1.1.8.2.apk";
        Process p = runtime.exec(ccString);

        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

        StringBuilder sb = new StringBuilder();
        while (br.readLine() != null) {
            sb.append(br.readLine() + "<br/>");
        }
        p.destroy();
        p = null;
        return sb.toString();
    } catch (FileNotFoundException fe) {
        return fe.getMessage();
    } catch (IOException ioe) {
        return ioe.getMessage();
    }

}