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:com.appspresso.api.fs.FileSystemUtils.java

/**
 * InputStream  path?  ? ./*w  w w .  ja v  a2s  . c o  m*/
 * 
 * @param inputStream ? InputStream
 * @param destFilePath  ??  path
 * @param overwrite  path? ? ??   ? 
 * @return ? {@literal true},   {@literal false}
 * @throws IOException ??   ?.
 */
public static boolean copy(InputStream inputStream, String destFilePath, boolean overwrite) throws IOException {
    File destFile = new File(destFilePath);
    File parent = destFile.getParentFile();
    if (!parent.exists() && !parent.mkdirs() && !parent.mkdir()) {
        return false;
    }

    if (destFile.exists()) {
        if (!overwrite) {
            return false;
        }
        if (!destFile.delete()) {
            return false;
        }
    }

    if (!destFile.createNewFile()) {
        return false;
    }

    FileOutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream(destFile);
        BufferedOutputStream bOutputStream = new BufferedOutputStream(outputStream);

        byte[] buffer = new byte[BUFFER_SIZE];
        int length = -1;
        while ((length = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
            bOutputStream.write(buffer, 0, length);
        }
        bOutputStream.flush();
        return true;
    } finally {
        closeQuietly(inputStream);
        closeQuietly(outputStream);
    }
}

From source file:oneDrive.OneDriveAPI.java

public static void uploadFile(String filePath) {
    URLConnection urlconnection = null;
    try {// ww w. ja  v  a2s  .  com
        File file = new File(UPLOAD_PATH + filePath);
        URL url = new URL(DRIVE_PATH + file.getName() + ":/content");
        urlconnection = url.openConnection();
        urlconnection.setDoOutput(true);
        urlconnection.setDoInput(true);

        if (urlconnection instanceof HttpURLConnection) {
            try {
                ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
                ((HttpURLConnection) urlconnection).setRequestProperty("Content-type",
                        "application/octet-stream");
                ((HttpURLConnection) urlconnection).addRequestProperty("Authorization",
                        "Bearer " + ACCESS_TOKEN);
                ((HttpURLConnection) urlconnection).connect();

            } catch (ProtocolException e) {
                e.printStackTrace();
            }
        }

        BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int i;
        // read byte by byte until end of stream
        while ((i = bis.read()) >= 0) {
            bos.write(i);
        }
        bos.flush();
        bos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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

/**
 * <p><em>Title: Create a File from a Base64 encoded String</em></p>
 * <p>Description: Method creates a file from the bytestream 
 * representing the original PDF, that should be converted</p>
 * // w ww.j  a va  2 s.c o  m
 * @param stream <code>String</code> 
 * @return <code>String</code> Filename of newly created temporary File
 */
public static String saveBase64ByteStringToFile(File outputFile, String stream) {
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    try {
        fos = new FileOutputStream(outputFile);
        bos = new BufferedOutputStream(fos);
        bos.write(Base64.decodeBase64(stream.getBytes("UTF-8")));
        bos.flush();
        bos.close();

    } catch (IOException ioExc) {
        log.error(ioExc);
    } 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);
            }
        }
    }
    return outputFile.getName();
}

From source file:net.amigocraft.mpt.util.MiscUtil.java

public static boolean unzip(ZipFile zip, File dest, List<String> files) throws MPTException {
    boolean returnValue = true;
    try {/*  w ww .ja v  a 2 s. c  om*/
        List<String> existingDirs = new ArrayList<>();
        Enumeration<? extends ZipEntry> en = zip.entries();
        entryLoop: while (en.hasMoreElements()) {
            ZipEntry entry = en.nextElement();
            String name = entry.getName().startsWith("./")
                    ? entry.getName().substring(2, entry.getName().length())
                    : entry.getName();
            File file = new File(dest, name);
            if (entry.isDirectory()) {
                if (file.exists()) {
                    if (DISALLOW_MERGE) {
                        existingDirs.add(name);
                        if (VERBOSE)
                            Main.log.warning("Refusing to extract directory " + name + ": already exists");
                    }
                }
            } else {
                files.add(name);
                for (String dir : DISALLOWED_DIRECTORIES) {
                    if (file.getPath().startsWith(dir)) {
                        if (VERBOSE)
                            Main.log.warning("Refusing to extract " + name + " from " + zip.getName()
                                    + ": parent directory \"" + dir + "\" is not allowed");
                        continue entryLoop;
                    }
                }
                if (DISALLOW_MERGE) {
                    for (String dir : existingDirs) {
                        if (file.getPath().substring(2, file.getPath().length()).replace(File.separator, "/")
                                .startsWith(dir)) {
                            continue entryLoop;
                        }
                    }
                }
                if (!DISALLOW_OVERWRITE || !file.exists()) {
                    file.getParentFile().mkdirs();
                    for (String ext : DISALLOWED_EXTENSIONS) {
                        if (file.getName().endsWith(ext)) {
                            if (VERBOSE)
                                Main.log.warning("Refusing to extract " + name + " from " + zip.getName()
                                        + ": extension \"" + ext + "\" is not allowed");
                            returnValue = false;
                            continue entryLoop;
                        }
                    }
                    BufferedInputStream bIs = new BufferedInputStream(zip.getInputStream(entry));
                    int b;
                    byte[] buffer = new byte[1024];
                    FileOutputStream fOs = new FileOutputStream(file);
                    BufferedOutputStream bOs = new BufferedOutputStream(fOs, 1024);
                    while ((b = bIs.read(buffer, 0, 1024)) != -1)
                        bOs.write(buffer, 0, b);
                    bOs.flush();
                    bOs.close();
                    bIs.close();
                } else {
                    if (VERBOSE)
                        Main.log.warning(
                                "Refusing to extract " + name + " from " + zip.getName() + ": already exists");
                    returnValue = false;
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace(); //TODO
        throw new MPTException(ERROR_COLOR + "Failed to extract archive!");
    }
    return returnValue;
}

From source file:com.github.jsonj.tools.JsonSerializer.java

/**
 * Writes the object out as json./*  w ww .  j  a  v a 2  s  .  c o  m*/
 * 
 * @param out
 *            output writer
 * @param json
 *            a {@link JsonElement}
 * @param pretty
 *            if true, a properly indented version of the json is written
 * @throws IOException
 *             if there is a problem writing to the stream
 */
public static void serialize(final OutputStream out, final JsonElement json, final boolean pretty)
        throws IOException {
    BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
    OutputStreamWriter w = new OutputStreamWriter(bufferedOut, UTF8);
    if (pretty) {
        serialize(w, json, pretty);
    } else {
        json.serialize(w);
        bufferedOut.flush();
    }
}

From source file:com.uberspot.storageutils.StorageUtils.java

/** Save the given string to a file in external storage
 * @param obj the object to save//from www.jav  a2  s .c o m
 * @param directory the directory in the SD card to save it into
 * @param fileName the name of the file
 * @param overwrite if set to true the file will be overwritten if it already exists
 * @return true if the file was written successfully, false otherwise
 */
public static boolean saveStringToExternalStorage(String obj, String directory, String fileName,
        boolean overwrite) {
    if (!directory.startsWith(File.separator))
        directory = File.separator + directory;

    File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + directory);
    if (!dir.exists())
        dir.mkdirs();

    File file = new File(dir, fileName);
    if (file.exists() && !overwrite)
        return false;
    BufferedOutputStream output = null;
    try {
        output = new BufferedOutputStream(new FileOutputStream(file));
        output.write(obj.getBytes());
        output.flush();
        return true;
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (output != null)
            try {
                output.close();
            } catch (IOException e) {
            }
    }
    return false;
}

From source file:com.jaspersoft.jasperserver.war.OlapGetChart.java

/**
 * Binary streams the specified file to the HTTP response in 1KB chunks
 *
 * @param file The file to be streamed./*from w w w  .  j a  v  a 2s.c o  m*/
 * @param response The HTTP response object.
 * @param mimeType The mime type of the file, null allowed.
 *
 * @throws IOException  if there is an I/O problem.
 * @throws FileNotFoundException  if the file is not found.
 */
public static void sendTempFile(File file, HttpServletResponse response, String mimeType)
        throws IOException, FileNotFoundException {

    if (file.exists()) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

        //  Set HTTP headers
        if (mimeType != null) {
            response.setHeader("Content-Type", mimeType);
        }
        response.setHeader("Content-Length", String.valueOf(file.length()));
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        response.setHeader("Last-Modified", sdf.format(new Date(file.lastModified())));

        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        byte[] input = new byte[1024];
        boolean eof = false;
        while (!eof) {
            int length = bis.read(input);
            if (length == -1) {
                eof = true;
            } else {
                bos.write(input, 0, length);
            }
        }
        bos.flush();
        bis.close();
        bos.close();
    } else {
        throw new FileNotFoundException(file.getAbsolutePath());
    }
    return;
}

From source file:com.example.tom.tryveg.carousel.AppUtils.java

/**
 * copies files on the native filesystem, optional unzip
 * //from w ww .  java 2s .  c  o  m
 */
public static void AssetFileCopy(Context context, String PathDest, String assetName, boolean gunzip) {
    try {

        File fdOut = new File(PathDest);
        fdOut.createNewFile();
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fdOut));
        InputStream in = null;
        if (gunzip)
            in = new GZIPInputStream(context.getAssets().open(assetName));
        else
            in = new BufferedInputStream(context.getAssets().open(assetName));
        //copy file content
        int length;
        byte buffer[] = new byte[4096];
        while ((length = in.read(buffer, 0, 4096)) != -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
        out.close();
        in.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:net.vexelon.myglob.utils.Utils.java

/**
 * Write input stream data to PRIVATE internal storage file.
 * @param context/*from w w  w  . j a va 2  s  . c o m*/
 * @param source
 * @param internalStorageName
 * @throws IOException
 */
public static void writeToInternalStorage(Context context, InputStream source, String internalStorageName)
        throws IOException {

    FileOutputStream fos = null;
    try {
        fos = context.openFileOutput(internalStorageName, Context.MODE_PRIVATE);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        BufferedInputStream bis = new BufferedInputStream(source);
        byte[] buffer = new byte[4096];
        int read = -1;
        while ((read = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, read);
        }
        bos.flush();
        bos.close();
    } catch (FileNotFoundException e) {
        throw new IOException(e.getMessage());
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
        try {
            if (source != null)
                source.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.elasticsearch.river.email.EmailToJson.java

private static void saveFile(InputStream is, String destDir, String fileName)
        throws FileNotFoundException, IOException {
    BufferedInputStream bis = new BufferedInputStream(is);
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(destDir + fileName)));
    int len = -1;
    while ((len = bis.read()) != -1) {
        bos.write(len);/* w  w w.j av a  2 s.c  o  m*/
        bos.flush();
    }
    bos.close();
    bis.close();
}