Example usage for java.io FileOutputStream flush

List of usage examples for java.io FileOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.alibaba.otter.shared.common.utils.NioUtilsPerformance.java

public static void mappedTest(File source, File target) throws Exception {
    FileInputStream fis = null;//from ww  w  . jav  a  2 s.c  o  m
    FileOutputStream fos = null;
    MappedByteBuffer mapbuffer = null;

    try {
        long fileSize = source.length();
        final byte[] outputData = new byte[(int) fileSize];
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);
        FileChannel sChannel = fis.getChannel();

        target.createNewFile();

        mapbuffer = sChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);
        for (int i = 0; i < fileSize; i++) {
            outputData[i] = mapbuffer.get();
        }

        mapbuffer.clear();
        fos.write(outputData);
        fos.flush();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);

        if (mapbuffer == null) {
            return;
        }

        final Object buffer = mapbuffer;

        AccessController.doPrivileged(new PrivilegedAction() {

            public Object run() {
                try {
                    Method clean = buffer.getClass().getMethod("cleaner", new Class[0]);

                    if (clean == null) {
                        return null;
                    }
                    clean.setAccessible(true);
                    sun.misc.Cleaner cleaner = (sun.misc.Cleaner) clean.invoke(buffer, new Object[0]);
                    cleaner.clean();
                } catch (Throwable ex) {
                }

                return null;
            }
        });
    }
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

public static void createThumnail(File file) {
    String name = file.getName();
    String filePath = file.getAbsolutePath();
    Bitmap bm;//ww w .  j  av a 2  s.  c  o  m

    if ((file.toString().contains(ConstantKeys.EXTENSION_JPG))
            || (file.toString().contains(ConstantKeys.EXTENSION_PNG))
            || (file.toString().contains(ConstantKeys.EXTENSION_JPEG))) {
        bm = decodeSampledBitmapFromPath(filePath, 250, 250);
        name = name.replace(ConstantKeys.EXTENSION_JPG, ConstantKeys.STRING_DEFAULT);

    } else {
        bm = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.MINI_KIND);
        name = name.replace(ConstantKeys.EXTENSION_3GP, ConstantKeys.STRING_DEFAULT);

    }

    if (bm == null) {
        log.error("Error creating thumbnail");
        return;
    }

    File f = new File(getDir(), name + ConstantKeys.THUMBNAIL + ConstantKeys.EXTENSION_JPG);
    try {
        f.createNewFile();
    } catch (IOException e1) {
        log.error("Error creating file for thumbnail", e1);
        return;
    }
    // Convert bitmap to byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bm.compress(CompressFormat.PNG, 0, bos);
    byte[] bitmapdata = bos.toByteArray();
    // write the bytes in file
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(f);
        fos.write(bitmapdata);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        log.debug("Error creagint thumnail", e);
    }

    bm = null;
    System.gc();
}

From source file:uploadProcess.java

public static boolean encrypt(String path, FileItemStream item, String patientID) {
    try {//from w ww.  java2s. c o  m
        File mainFolder = new File(path + File.separator + "Encrypt");
        if (!mainFolder.exists()) {
            mainFolder.mkdir();
        }
        File patientFolder = new File(mainFolder + File.separator + patientID);
        if (!patientFolder.exists()) {
            patientFolder.mkdir();
        }
        String ukey = GetKey.getPatientKey(patientID);
        InputStream fis = item.openStream();

        FileOutputStream fos = new FileOutputStream(
                patientFolder.getAbsolutePath() + File.separator + item.getName());
        byte[] k = ukey.getBytes();
        SecretKeySpec key = new SecretKeySpec(k, "AES");
        System.out.println(key);
        Cipher enc = Cipher.getInstance("AES");
        enc.init(Cipher.ENCRYPT_MODE, key);
        CipherOutputStream cos = new CipherOutputStream(fos, enc);
        byte[] buf = new byte[1024];
        int read;
        while ((read = fis.read(buf)) != -1) {
            cos.write(buf, 0, read);
        }
        fis.close();
        fos.flush();
        cos.close();

        //Upload File to cloud
        DropboxUpload upload = new DropboxUpload();
        upload.uploadFile(patientFolder, item.getName(), StoragePath.getDropboxDir() + patientID);
        DeleteDirectory.delete(patientFolder);

        return true;
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
    return false;
}

From source file:uploadProcess.java

public static boolean decrypt(File inputFolder, String fileName, String patientID, String viewKey) {
    try {//from w  w  w .  j ava  2 s. c  o  m

        String ukey = GetKey.getPatientKey(patientID);
        if (viewKey.equals(ukey)) {
            //Download File from Cloud..
            DropboxUpload download = new DropboxUpload();
            download.downloadFile(fileName, StoragePath.getDropboxDir() + patientID, inputFolder);

            File inputFile = new File(inputFolder.getAbsolutePath() + File.separator + fileName);
            FileInputStream fis = new FileInputStream(inputFile);
            File outputFolder = new File(inputFolder.getAbsolutePath() + File.separator + "temp");
            if (!outputFolder.exists()) {
                outputFolder.mkdir();
            }
            FileOutputStream fos = new FileOutputStream(
                    outputFolder.getAbsolutePath() + File.separator + fileName);
            byte[] k = ukey.getBytes();
            SecretKeySpec key = new SecretKeySpec(k, "AES");
            Cipher enc = Cipher.getInstance("AES");
            enc.init(Cipher.DECRYPT_MODE, key);
            CipherOutputStream cos = new CipherOutputStream(fos, enc);
            byte[] buf = new byte[1024];
            int read;
            while ((read = fis.read(buf)) != -1) {
                cos.write(buf, 0, read);
            }
            fis.close();
            fos.flush();
            cos.close();
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
    return false;
}

From source file:edu.stanford.epad.epadws.service.TCIAService.java

private static void writePropertiesFile(File storeDir, String project, String session, String user) {

    String projectName = "XNATProjectName=" + project;
    String sessionName = "XNATSessionID=" + session;
    String userName = "XNATUserName=" + user;

    try {//from ww w  . j ava 2s.  c  o  m
        File properties = new File(storeDir, "xnat_upload.properties");
        if (!properties.exists()) {
            properties.createNewFile();
        }
        FileOutputStream fop = new FileOutputStream(properties, false);

        fop.write(projectName.getBytes());
        fop.write("\n".getBytes());
        fop.write(sessionName.getBytes());
        fop.write("\n".getBytes());
        fop.write(userName.getBytes());
        fop.write("\n".getBytes());

        fop.flush();
        fop.close();

    } catch (IOException e) {
        log.info("Error writing properties file");
        e.printStackTrace();
    }
}

From source file:com.opendoorlogistics.core.tables.io.PoiIO.java

private static void saveWorkbook(File file, Workbook wb) {
    try {/*  w w  w.  j  a  v a2  s . c  o  m*/
        FileOutputStream fos = new FileOutputStream(file, false);
        wb.write(fos);
        fos.flush();
        fos.close();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:com.polyvi.xface.util.XFileUtils.java

/**
 * /*from w w  w.j  ava 2s  .c  o m*/
 *
 * @param filePath
 *            ?
 * @param data
 *            ??
 * @return ??
 */
public static long write(String fileName, String data, int position) throws FileNotFoundException, IOException {
    boolean append = false;
    if (position > 0) {
        truncateFile(fileName, position);
        append = true;
    }

    byte[] rawData = data.getBytes();
    ByteArrayInputStream in = new ByteArrayInputStream(rawData);
    FileOutputStream out = new FileOutputStream(fileName, append);
    byte buff[] = new byte[rawData.length];
    in.read(buff, 0, buff.length);
    out.write(buff, 0, rawData.length);
    out.flush();
    out.close();

    return data.length();
}

From source file:Main.java

public static void compressAFileToZip(File zip, File source) throws IOException {
    Log.d("source: " + source.getAbsolutePath(), ", length: " + source.length());
    Log.d("zip:", zip.getAbsolutePath());
    zip.getParentFile().mkdirs();//w w  w .j a v a2 s.c o  m
    File tempFile = new File(zip.getAbsolutePath() + ".tmp");
    FileOutputStream fos = new FileOutputStream(tempFile);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    ZipOutputStream zos = new ZipOutputStream(bos);
    ZipEntry zipEntry = new ZipEntry(source.getName());
    zipEntry.setTime(source.lastModified());
    zos.putNextEntry(zipEntry);

    FileInputStream fis = new FileInputStream(source);
    BufferedInputStream bis = new BufferedInputStream(fis);
    byte[] bArr = new byte[4096];
    int byteRead = 0;
    while ((byteRead = bis.read(bArr)) != -1) {
        zos.write(bArr, 0, byteRead);
    }
    zos.flush();
    zos.closeEntry();
    zos.close();
    Log.d("zipEntry: " + zipEntry, "compressedSize: " + zipEntry.getCompressedSize());
    bos.flush();
    fos.flush();
    bos.close();
    fos.close();
    bis.close();
    fis.close();
    zip.delete();
    tempFile.renameTo(zip);
}

From source file:com.example.heya.couchdb.ConnectionHandler.java

/**
 * Get a File object from an URL/*from w ww. ja  v a2s .com*/
 * 
 * @param url
 * @param path
 * @return
 * @throws IOException 
 * @throws ClientProtocolException 
 * @throws SpikaException 
 * @throws JSONException 
 * @throws IllegalStateException 
 * @throws SpikaForbiddenException 
 */
public static void getFile(String url, File file, String userId, String token) throws ClientProtocolException,
        IOException, SpikaException, IllegalStateException, JSONException, SpikaForbiddenException {

    File mFile = file;

    //URL mUrl = new URL(url); // you can write here any link

    InputStream is = httpGetRequest(url, userId);
    BufferedInputStream bis = new BufferedInputStream(is);

    ByteArrayBuffer baf = new ByteArrayBuffer(20000);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }

    /* Convert the Bytes read to a String. */
    FileOutputStream fos = new FileOutputStream(mFile);
    fos.write(baf.toByteArray());
    fos.flush();
    fos.close();
    is.close();

}

From source file:com.pclinuxos.rpm.util.FileUtils.java

/**
 * The method extracts a srpm into the default directory used by the program (/home/<user>/RCEB/srpms/tmp)
 * /*from  w ww. ja  v  a 2 s  .c  o m*/
 * @param srpm the srpm to extract
 * @return 0 if the extraction was successfully, -1 if a IOException occurred, -2 if a InterruptException
 *  occurred. Values > 0 for return codes of the rpm2cpio command.
 */
public static int extractSrpm(String srpm) {

    int returnCode = 0;

    try {

        Process extractProcess = Runtime.getRuntime()
                .exec("rpm2cpio " + FileConstants.SRCSRPMS.getAbsolutePath() + "/" + srpm);
        // 64kb buffer
        byte[] buffer = new byte[0xFFFF];
        InputStream inread = extractProcess.getInputStream();

        FileOutputStream out = new FileOutputStream(new File(FileConstants.F4SRPMEX + "archive.cpio"));

        while (inread.read(buffer) != -1) {

            out.write(buffer);
        }

        returnCode = extractProcess.waitFor();

        if (returnCode == 0) {

            CpioArchiveInputStream cpioIn = new CpioArchiveInputStream(
                    new FileInputStream(FileConstants.F4SRPMEX + "archive.cpio"));
            CpioArchiveEntry cpEntry;

            while ((cpEntry = cpioIn.getNextCPIOEntry()) != null) {

                FileOutputStream fOut = new FileOutputStream(FileConstants.F4SRPMEX + cpEntry.getName());
                // Do not make this buffer bigger it breaks the cpio decompression
                byte[] buffer2 = new byte[1];
                ArrayList<Byte> buf = new ArrayList<Byte>();

                while (cpioIn.read(buffer2) != -1) {

                    buf.add(buffer2[0]);
                }

                byte[] file = new byte[buf.size()];

                for (int i = 0; i < buf.size(); i++) {

                    file[i] = buf.get(i);
                }

                fOut.write(file);

                fOut.flush();
                fOut.close();
            }

            cpioIn.close();
        }
    } catch (IOException e) {

        returnCode = -1;
    } catch (InterruptedException e) {

        returnCode = -2;
    }

    new File(FileConstants.F4SRPMEX + "archive.cpio").delete();

    return returnCode;
}