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:io.cslinmiso.line.utils.Utility.java

/**
 * Java IO (java io write file)/*from w  ww  .ja  va2s  . com*/
 * 
 * @param inputData
 * @param filePath
 * @throws IOException
 */
public static void writeFile(InputStream inputData, String filePath) throws IOException {
    InputStream input = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(filePath);
        int size;
        byte[] buffer = new byte[1024];
        while ((size = inputData.read(buffer)) != -1) {
            fos.write(buffer, 0, size);
        }
        fos.flush();
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}

From source file:WarUtil.java

/**
 * WAR???????????//from  w w  w.  j  a  va 2 s .c  o  m
 * 
 * @param warFile
 * @param directory
 * @throws IOException
 */
public static void extractWar(File warFile, File directory) throws IOException {
    try {
        long timestamp = warFile.lastModified();
        File warModifiedTimeFile = new File(directory, LAST_MODIFIED_FILE);
        long lastModified = readLastModifiled(warModifiedTimeFile);

        if (timestamp == lastModified) {
            //      log.info("war file " + warFile.getName() + " not modified.");
            return;
        }
        if (directory.exists()) {
            //         IOUtil.forceRemoveDirectory(directory);
            directory.mkdir();
        }

        //         log.info("war extract start. warfile=" + warFile.getName());

        JarInputStream jin = new JarInputStream(new BufferedInputStream(new FileInputStream(warFile)));
        JarEntry entry = null;

        while ((entry = jin.getNextJarEntry()) != null) {
            File file = new File(directory, entry.getName());

            if (entry.isDirectory()) {
                if (!file.exists()) {
                    file.mkdirs();
                }
            } else {
                File dir = new File(file.getParent());
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                FileOutputStream fout = null;
                try {
                    fout = new FileOutputStream(file);
                    ResourceUtil.copyStream(jin, fout);
                } finally {
                    fout.flush();
                    fout.close();
                    fout = null;
                }

                if (entry.getTime() >= 0) {
                    file.setLastModified(entry.getTime());
                }
            }
        }

        writeLastModifiled(warModifiedTimeFile, timestamp);

        //log.info("war extract success. lastmodified=" + timestamp);
    } catch (IOException ioe) {
        //log.info("war extract fail.");
        throw ioe;
    }
}

From source file:net.sf.nmedit.jsynth.clavia.nordmodular.utils.NmUtils.java

public static void writePatch(NMPatch patch, File file) throws IOException, ParseException {
    FileOutputStream out = new FileOutputStream(file);
    try {//from ww  w  . j av  a2 s .  c  o  m
        writePatch(patch, out);
    } finally {
        out.flush();
        out.close();
    }
}

From source file:Main.java

private static Uri getUriFromAsset(Context mContext, String path) {
    File dir = mContext.getExternalCacheDir();

    if (dir == null) {
        Log.e(TAG, "Missing external cache dir");
        return Uri.EMPTY;
    }/*from  w  w w . j a  v  a2s . c om*/
    String resPath = path.replaceFirst("file:/", "www");
    String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
    String storage = dir.toString() + STORAGE_FOLDER;

    if (fileName == null || fileName.isEmpty()) {
        Log.e(TAG, "Filename is missing");
        return Uri.EMPTY;
    }

    File file = new File(storage, fileName);
    FileOutputStream outStream = null;
    InputStream inputStream = null;

    try {
        File fileStorage = new File(storage);
        if (!fileStorage.mkdir())
            Log.e(TAG, "Storage directory could not be created: " + storage);

        AssetManager assets = mContext.getAssets();
        outStream = new FileOutputStream(file);
        inputStream = assets.open(resPath);

        copyFile(inputStream, outStream);
        outStream.flush();
        outStream.close();
        return Uri.fromFile(file);
    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found: assets/" + resPath);
    } catch (IOException ioe) {
        Log.e(TAG, "IOException occured");
    } catch (SecurityException secEx) {
        Log.e(TAG, "SecurityException: directory creation denied");
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outStream != null) {
                outStream.flush();
                outStream.close();
            }
        } catch (IOException ioe) {
            Log.e(TAG, "IOException occured while closing/flushing streams");
        }
    }
    return Uri.EMPTY;
}

From source file:com.ecofactor.qa.automation.platform.util.FileUtil.java

/**
 * Download Mobile Zip File from jenkinsosx.ecofactor.com
 * @param webURL the web url/* w  w  w  . j ava2s . com*/
 * @param destinationPath the destination path
 */
public static void downloadFileFromURL(final String webURL, final String destinationPath) {

    LogUtil.setLogString(new StringBuilder("Download File from location :").append(webURL).toString(), true);
    try {
        final URL url = new URL(webURL);
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        final InputStream inStream = connection.getInputStream();
        final FileOutputStream outStream = new FileOutputStream(new File(destinationPath));
        final byte[] buf = new byte[1024];
        int inByte = inStream.read(buf);
        while (inByte >= 0) {
            outStream.write(buf, 0, inByte);
            inByte = inStream.read(buf);
        }
        outStream.flush();
        outStream.close();
    } catch (Exception e) {
        LOGGER.error("Error in download file", e);
    }
}

From source file:com.hoccer.tools.HttpHelper.java

public static HttpResponse fetchUriToFile(String uriString, String filename)
        throws IOException, HttpClientException, HttpServerException {

    HttpGet get = new HttpGet(uriString);
    HttpResponse response = executeHTTPMethod(get);
    HttpEntity entity = response.getEntity();

    FileOutputStream fstream = new FileOutputStream(filename);
    entity.writeTo(fstream);//from  w w  w.j  ava 2 s.  c  o  m
    fstream.flush();
    fstream.close();
    return response;
}

From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java

public static void outputStringToFile(String loggingIngo, String filePath) {
    try {/*from   ww  w.  j av a  2 s .  c o m*/
        File file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream op = new FileOutputStream(file);
        byte[] loggingIngoBytes = loggingIngo.getBytes();
        op.write(loggingIngoBytes);
        op.flush();
        op.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(DocumentProcessorUtil.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(DocumentProcessorUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.alibaba.dubbo.monitor.simple.SimpleMonitorService.java

private static void createChart(String key, String service, String method, String date, String[] types,
        Map<String, long[]> data, double[] summary, String path) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
    DecimalFormat numberFormat = new DecimalFormat("###,##0.##");
    TimeSeriesCollection xydataset = new TimeSeriesCollection();
    for (int i = 0; i < types.length; i++) {
        String type = types[i];//from w  ww  .j  a v  a2  s.c om
        TimeSeries timeseries = new TimeSeries(type);
        for (Map.Entry<String, long[]> entry : data.entrySet()) {
            try {
                timeseries.add(new Minute(dateFormat.parse(date + entry.getKey())), entry.getValue()[i]);
            } catch (ParseException e) {
                logger.error(e.getMessage(), e);
            }
        }
        xydataset.addSeries(timeseries);
    }
    JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(
            "max: " + numberFormat.format(summary[0])
                    + (summary[1] >= 0 ? " min: " + numberFormat.format(summary[1]) : "") + " avg: "
                    + numberFormat.format(summary[2])
                    + (summary[3] >= 0 ? " sum: " + numberFormat.format(summary[3]) : ""),
            toDisplayService(service) + "  " + method + "  " + toDisplayDate(date), key, xydataset, true, true,
            false);
    jfreechart.setBackgroundPaint(Color.WHITE);
    XYPlot xyplot = (XYPlot) jfreechart.getPlot();
    xyplot.setBackgroundPaint(Color.WHITE);
    xyplot.setDomainGridlinePaint(Color.GRAY);
    xyplot.setRangeGridlinePaint(Color.GRAY);
    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinesVisible(true);
    DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
    dateaxis.setDateFormatOverride(new SimpleDateFormat("HH:mm"));
    BufferedImage image = jfreechart.createBufferedImage(600, 300);
    try {
        if (logger.isInfoEnabled()) {
            logger.info("write chart: " + path);
        }
        File methodChartFile = new File(path);
        File methodChartDir = methodChartFile.getParentFile();
        if (methodChartDir != null && !methodChartDir.exists()) {
            methodChartDir.mkdirs();
        }
        FileOutputStream output = new FileOutputStream(methodChartFile);
        try {
            ImageIO.write(image, "png", output);
            output.flush();
        } finally {
            output.close();
        }
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
    }
}

From source file:com.easysoft.build.utils.PatchUtil.java

/**
 * ?SQL/*from w w  w  .j a va 2  s. c  om*/
 * @param vpSqls ???patchFile
 * @param patchFile ???
 * @param encoding ?
 * @throws java.io.IOException
 */
public static void mergeSqlTo(File[] vpSqls, File patchFile, String encoding) throws IOException {
    if (encoding == null)
        encoding = "UTF-8";
    StringBuilder sb = readFile(patchFile, encoding);
    for (File sqlFile : vpSqls) {
        StringBuilder sql = readFile(sqlFile, encoding);
        replaceSection(sb, sqlFile.getName(), sql.toString());
    }
    patchFile.getParentFile().mkdirs();
    FileOutputStream out = new FileOutputStream(patchFile);
    out.write(sb.toString().getBytes(encoding));
    out.flush();
    out.close();
}

From source file:com.kabootar.GlassMemeGenerator.ImageOverlay.java

public static boolean saveToSD(final Bitmap overlaid, final String sdPath, final String fileName) {
    boolean isItSaved = false;
    new AsyncTask<Void, Void, Void>() {

        @Override/*from ww  w  .j a  va  2s  .  com*/
        protected Void doInBackground(Void... arg0) {

            File image = new File(sdPath, fileName);

            FileOutputStream outStream;
            try {

                outStream = new FileOutputStream(image);
                //resize image
                Bitmap newoverlaid = getResizedBitmap(overlaid, 1000, 1362);
                newoverlaid.compress(Bitmap.CompressFormat.PNG, 100, outStream);

                outStream.flush();
                outStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
            int width = bm.getWidth();
            int height = bm.getHeight();
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            // CREATE A MATRIX FOR THE MANIPULATION
            Matrix matrix = new Matrix();
            // RESIZE THE BIT MAP
            matrix.postScale(scaleWidth, scaleHeight);

            // "RECREATE" THE NEW BITMAP
            Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
            return resizedBitmap;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
    }.execute();

    return isItSaved;
}