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.thejustdo.util.Utils.java

/**
 * Given a temporal directory and getting help from the Constants class, 
 * we may copy if necessary all the info required for the correct generation 
 * of PDF files./*from  www.j a va  2 s. c o  m*/
 * @param tmp Where is the temporal directory of the server.
 * @return The directory in which the temporal files can be saved.
 */
public static File preparePDFDirs(File tmp, ServletContext sc) throws IOException {
    // 0. Creating the pdf directory if needed.
    File pdf = new File(tmp, Constants.TMP_PDF);

    if (pdf.exists()) {
        log.info(String.format("Found temporal directory for pdfs %s", pdf.getAbsolutePath()));
        return pdf;
    }

    // 1. Creating the structure.
    pdf.mkdirs();

    File tmpImg = new File(pdf, "images");
    tmpImg.mkdirs();

    // 2. Copying content.
    InputStream is;
    FileOutputStream os;
    File goal;
    int read;
    byte bytes[] = new byte[1024];
    for (String s : Constants.PDF_IMGS) {
        log.info(String.format("Copying file %s%s", Constants.PDF_IMAGE_PATH, s));
        is = sc.getResourceAsStream(Constants.PDF_IMAGE_PATH + s);
        goal = new File(tmpImg, s);
        os = new FileOutputStream(goal);

        // Writing file.
        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }

        // Done writing.
        os.flush();
        os.close();
        is.close();
    }

    // File origin = new File(sc.getRealPath(Constants.PDF_IMAGE_PATH));
    // FileUtils.copyDirectoryToDirectory(origin, pdf);
    log.info(String.format("Created pdf data at: %s", pdf.getAbsolutePath()));

    return pdf;
}

From source file:fr.shywim.antoinedaniel.utils.Utils.java

/**
 * Download a file from the CDN server./*from w  ww . j av a  2s .  co m*/
 * (Note to self: all last three params could be determined by {@link java.io.File#getPath})
 * @param context Any context.
 * @param dst Local {@link java.io.File} to save.
 * @param fileName Name of the distant file to download.
 * @param folder Folder of the distant file to download.
 * @param ext Extension of the distant file to download.
 * @return true if file has been successfully downloaded, false in any other case.
 */
public static boolean downloadFileFromCdn(Context context, File dst, String fileName, String folder, String ext,
        boolean force) throws IOException {
    int count;
    InputStream input;
    FileOutputStream output;
    final String cdnLink = context.getResources().getString(R.string.cdn_link);

    if (force || !dst.exists()) {
        if (force || dst.createNewFile()) {
            URL url = new URL(cdnLink + folder + fileName + ext);
            input = new BufferedInputStream(url.openStream(), 4096);
            byte data[] = new byte[2048];
            output = new FileOutputStream(dst);
            while ((count = input.read(data)) != -1) {
                output.write(data, 0, count);
            }
            output.flush();
            input.close();
            output.close();
        } else {
            return false;
        }
    }
    return true;
}

From source file:at.tugraz.sss.serv.util.SSFileU.java

public static void writeFileBytes(final FileOutputStream fileOut, final byte[] bytes, final Integer length)
        throws SSErr {

    try {/* w w  w. j av a2  s  .  c om*/

        fileOut.write(bytes, 0, length);
        fileOut.flush();

    } catch (Exception error) {
        SSServErrReg.regErrThrow(error);
    } finally {

        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (IOException ex) {
                SSLogU.err(ex);
            }
        }
    }
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.FileUploader.java

/**
 * ??file/* www  .j  av a  2s. c  om*/
 *
 * @param in
 * @return
 * @throws IOException
 */
public static File createTempFile(InputStream in) throws IOException, IllegalArgumentException {
    if (null == in) {
        XLog.e(CLASS_NAME, "createTempFile methods: param is null");
        throw new IllegalArgumentException();
    }
    final File tempFile = File.createTempFile(PREFIX, SUFFIX);
    tempFile.deleteOnExit();
    FileOutputStream out = new FileOutputStream(tempFile);
    try {
        byte[] buffer = new byte[XConstant.BUFFER_LEN];
        int len;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
    } catch (IOException e) {
        XLog.e(CLASS_NAME, "Create temp file failed");
        throw new IOException();
    } finally {
        if (null != out) {
            out.flush();
            out.close();
        }
        in.close();
    }
    return tempFile;
}

From source file:com.github.commonclasses.network.DownloadUtils.java

public static long download(String urlStr, File dest, boolean append, DownloadListener downloadListener)
        throws Exception {
    int downloadProgress = 0;
    long remoteSize = 0;
    int currentSize = 0;
    long totalSize = -1;

    if (!append && dest.exists() && dest.isFile()) {
        dest.delete();//from  w  ww.ja v a 2  s  .  co m
    }

    if (append && dest.exists() && dest.exists()) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(dest);
            currentSize = fis.available();
        } catch (IOException e) {
            throw e;
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }

    HttpGet request = new HttpGet(urlStr);
    request.setHeader("Content-Type", "application/x-www-form-urlencoded");

    if (currentSize > 0) {
        request.addHeader("RANGE", "bytes=" + currentSize + "-");
    }

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, DATA_TIMEOUT);
    HttpClient httpClient = new DefaultHttpClient(params);

    InputStream is = null;
    FileOutputStream os = null;
    try {
        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            is = response.getEntity().getContent();
            remoteSize = response.getEntity().getContentLength();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                is = new GZIPInputStream(is);
            }
            os = new FileOutputStream(dest, append);
            byte buffer[] = new byte[DATA_BUFFER];
            int readSize = 0;
            while ((readSize = is.read(buffer)) > 0) {
                os.write(buffer, 0, readSize);
                os.flush();
                totalSize += readSize;
                if (downloadListener != null) {
                    downloadProgress = (int) (totalSize * 100 / remoteSize);
                    downloadListener.downloading(downloadProgress);
                }
            }
            if (totalSize < 0) {
                totalSize = 0;
            }
        }
    } catch (Exception e) {
        if (downloadListener != null) {
            downloadListener.exception(e);
        }
        e.printStackTrace();
    } finally {
        if (os != null) {
            os.close();
        }
        if (is != null) {
            is.close();
        }
    }

    if (totalSize < 0) {
        throw new Exception("Download file fail: " + urlStr);
    }

    if (downloadListener != null) {
        downloadListener.downloaded(dest);
    }

    return totalSize;
}

From source file:de.adesso.referencer.search.helper.MyHelpMethods.java

public static void saveObject2File(Object o, String filename) {

    FileOutputStream fop = null;
    File file;//from   w  ww.j a  v a  2  s  . c  o  m
    String content = gson.toJson(o);

    try {

        file = new File(filename);
        fop = new FileOutputStream(file);

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        // get the content in bytes
        byte[] contentInBytes = content.getBytes();

        fop.write(contentInBytes);
        fop.flush();
        fop.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fop != null) {
                fop.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.hmiard.blackwater.projects.Builder.java

/**
 * Appending a new server to a project./*from www .  j  a  v a2  s .  c o  m*/
 *
 * @param projectRoot String
 * @param serverName String
 * @param consoleListener ConsoleEmulator
 * @param needsDb Boolean
 */
public static Boolean appendServer(String projectRoot, String serverName, ConsoleEmulator consoleListener,
        Boolean needsDb) {

    try {
        serverName = serverName.substring(0, 1).toUpperCase() + serverName.substring(1).toLowerCase();
        String shortServerName = serverName;
        serverName += "Server";
        String src = projectRoot + "\\src\\" + serverName;
        File checker = new File(projectRoot + "\\src\\" + serverName);
        File composerJSON = new File(projectRoot + "\\composer.json");

        if (checker.exists() && checker.isDirectory()) {
            consoleListener.push("This server already exists ! Operation aborted.");
            return false;
        }
        if (!composerJSON.exists()) {
            consoleListener.push("File composer.json is missing ! Operation aborted.");
            return false;
        }

        if (needsDb)
            copyFolder(new File("resources/packages/DefaultApp"), new File(src));
        else
            copyFolder(new File("resources/packages/NoDbApp"), new File(src));

        FileOutputStream writer;
        File core = new File(src + "\\BlackwaterDefaultApp.php");
        File qf = new File(src + "\\DefaultAppQueryFactory.php");
        File bootstrap = new File(src + "\\bin\\init.php");

        String coreContent = readFile(core.getAbsolutePath());
        coreContent = coreContent.replace("BlackwaterDefaultApp", serverName);
        File newCore = new File(src + "\\" + serverName + ".php");
        if (newCore.createNewFile() && core.delete()) {
            writer = new FileOutputStream(newCore);
            writer.write(coreContent.getBytes());
            writer.flush();
            writer.close();
        }

        if (needsDb) {
            String qfContent = readFile(qf.getAbsolutePath());
            qfContent = qfContent.replace("BlackwaterDefaultApp", serverName);
            qfContent = qfContent.replace("DefaultApp", shortServerName);
            File newQf = new File(src + "\\" + shortServerName + "QueryFactory.php");
            if (newQf.createNewFile() && qf.delete()) {
                writer = new FileOutputStream(newQf);
                writer.write(qfContent.getBytes());
                writer.flush();
                writer.close();
            }
        }

        String bootsrapContent = readFile(bootstrap.getAbsolutePath());
        Random r = new Random();
        bootsrapContent = bootsrapContent.replace("Default", shortServerName);
        bootsrapContent = bootsrapContent.replace("8080", String.valueOf(r.nextInt(2000) + 7000));
        writer = new FileOutputStream(bootstrap);
        writer.write(bootsrapContent.getBytes());
        writer.flush();
        writer.close();

        JSONObject composer = new JSONObject(readFile(composerJSON.getAbsolutePath()));
        JSONObject autoload = composer.getJSONObject("autoload");
        JSONObject psr0 = autoload.getJSONObject("psr-0");
        psr0.put(serverName, "src");

        BufferedWriter cw = new BufferedWriter(new FileWriter(composerJSON.getAbsoluteFile()));
        String content = composer.toString(4).replaceAll("\\\\", "");
        cw.write(content);
        cw.close();

        consoleListener.push(serverName + " created !\n");

    } catch (JSONException | IOException e) {
        e.printStackTrace();
    }

    return true;
}

From source file:de.adesso.referencer.search.helper.MyHelpMethods.java

public static void save2File(Object r, String filename) {

    FileOutputStream fop = null;
    File file;/* w  ww.j av a2 s. c  om*/
    String content = gsonPretty.toJson(r);

    try {

        file = new File(filename);
        fop = new FileOutputStream(file);

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        // get the content in bytes
        byte[] contentInBytes = content.getBytes();

        fop.write(contentInBytes);
        fop.flush();
        fop.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fop != null) {
                fop.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.lurencun.cfuture09.androidkit.http.Http.java

/**
 * /*from w ww  .  j  av  a 2 s . c  o m*/
 *
 * @param url
 *            ?
 * @param savePath
 *            ??
 * @param overwrite
 *            ?
 * @throws IOException
 *             ??io
 */
public static void download(String url, File savePath, boolean overwrite) throws IOException {
    if (savePath == null) {
        throw new IOException("the second parameter couldn't be null");
    }
    if (savePath.exists() && (!overwrite || savePath.isDirectory())) {
        throw new IOException("the file specified is exist or cannot be overwrite");
    }
    savePath.getParentFile().mkdirs();

    HttpURLConnection connection = null;
    InputStream input = null;
    FileOutputStream output = null;
    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        input = connection.getInputStream();
        output = new FileOutputStream(savePath);
        byte[] buffer = new byte[BUFFER_SIZE];
        int readSize = 0;
        while ((readSize = input.read(buffer)) != -1) {
            output.write(buffer, 0, readSize);
        }
        output.flush();
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

/**
 * Sends an HTTP GET request to a url/*from  w  ww . jav a 2 s .c o m*/
 *
 * @param urlStr            - The URL of the server. (Example: " http://www.yahoo.com/search")
 * @param file              the output file. If it is a folder, it tries to get the file name from the header.
 * @param requestParameters - all the request parameters (Example: "param1=val1&param2=val2").
 *                          Note: This method will add the question mark (?) to the request -
 *                          DO NOT add it yourself
 * @param user              user.
 * @param password          password.
 * @return the file written.
 * @throws Exception if something goes wrong.
 */
public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user,
        String password) throws Exception {
    if (requestParameters != null && requestParameters.length() > 0) {
        urlStr += "?" + requestParameters;
    }
    HttpURLConnection conn = makeNewConnection(urlStr);
    conn.setRequestMethod("GET");
    // conn.setDoOutput(true);
    conn.setDoInput(true);
    // conn.setChunkedStreamingMode(0);
    conn.setUseCaches(false);

    if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) {
        conn.setRequestProperty("Authorization", getB64Auth(user, password));
    }
    conn.connect();

    if (file.isDirectory()) {
        // try to get the header
        String headerField = conn.getHeaderField("Content-Disposition");
        String fileName = null;
        if (headerField != null) {
            String[] split = headerField.split(";");
            for (String string : split) {
                String pattern = "filename=";
                if (string.toLowerCase().startsWith(pattern)) {
                    fileName = string.replaceFirst(pattern, "");
                    break;
                }
            }
        }
        if (fileName == null) {
            // give a name
            fileName = "FILE_" + TimeUtilities.INSTANCE.TIMESTAMPFORMATTER_LOCAL.format(new Date());
        }
        file = new File(file, fileName);
    }

    InputStream in = null;
    FileOutputStream out = null;
    try {
        in = conn.getInputStream();
        out = new FileOutputStream(file);

        byte[] buffer = new byte[(int) maxBufferSize];
        int bytesRead = in.read(buffer, 0, (int) maxBufferSize);
        while (bytesRead > 0) {
            out.write(buffer, 0, bytesRead);
            bytesRead = in.read(buffer, 0, (int) maxBufferSize);
        }
        out.flush();
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
        if (conn != null)
            conn.disconnect();
    }
    return file;
}