Example usage for java.io BufferedWriter flush

List of usage examples for java.io BufferedWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:madkitgroupextension.export.Export.java

public static void saveAndIncrementBuild() throws IOException {
    MadKitGroupExtension.VERSION.setBuildNumber(MadKitGroupExtension.VERSION.getBuildNumber() + 1);
    FileWriter fw = new FileWriter(new File("build.txt"));
    BufferedWriter b = new BufferedWriter(fw);
    b.write(Integer.toString(MadKitGroupExtension.VERSION.getBuildNumber()));
    b.flush();
    b.close();/*  w w w  .  ja v  a2s. co m*/
    fw.close();
}

From source file:net.sourceforge.eclipsetrader.charts.ChartsPlugin.java

public static void saveDefaultChart(Chart chart) {
    Log logger = LogFactory.getLog(ChartsPlugin.class);
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //$NON-NLS-1$

    try {/*from  w  w w  .ja  v a 2 s. c o m*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.getDOMImplementation().createDocument(null, "chart", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();

        Element node = document.createElement("title"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(chart.getTitle()));
        root.appendChild(node);
        node = document.createElement("compression"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getCompression())));
        root.appendChild(node);
        node = document.createElement("period"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getPeriod())));
        root.appendChild(node);
        node = document.createElement("autoScale"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.isAutoScale())));
        root.appendChild(node);
        if (chart.getBeginDate() != null) {
            node = document.createElement("begin"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getBeginDate())));
            root.appendChild(node);
        }
        if (chart.getEndDate() != null) {
            node = document.createElement("end"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getEndDate())));
            root.appendChild(node);
        }
        for (int r = 0; r < chart.getRows().size(); r++) {
            ChartRow row = (ChartRow) chart.getRows().get(r);
            row.setId(new Integer(r));

            Element rowNode = document.createElement("row"); //$NON-NLS-1$
            root.appendChild(rowNode);

            for (int t = 0; t < row.getTabs().size(); t++) {
                ChartTab tab = (ChartTab) row.getTabs().get(t);
                tab.setId(new Integer(t));

                Element tabNode = document.createElement("tab"); //$NON-NLS-1$
                tabNode.setAttribute("label", tab.getLabel()); //$NON-NLS-1$
                rowNode.appendChild(tabNode);

                for (int i = 0; i < tab.getIndicators().size(); i++) {
                    ChartIndicator indicator = (ChartIndicator) tab.getIndicators().get(i);
                    indicator.setId(new Integer(i));

                    Element indicatorNode = document.createElement("indicator"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", indicator.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = indicator.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) indicator.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }

                for (int i = 0; i < tab.getObjects().size(); i++) {
                    ChartObject object = (ChartObject) tab.getObjects().get(i);
                    object.setId(new Integer(i));

                    Element indicatorNode = document.createElement("object"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", object.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = object.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) object.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }
            }
        }

        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$
        } catch (Exception e) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMSource source = new DOMSource(document);

        File file = ChartsPlugin.getDefault().getStateLocation().append("defaultChart.xml").toFile(); //$NON-NLS-1$

        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.flush();
        out.close();

    } catch (Exception e) {
        logger.error(e.toString(), e);
    }
}

From source file:net.naijatek.myalumni.util.utilities.FileUtil.java

/**
 * Write content to_email a fileName with the destEncoding
 * /*from  ww  w.j av a  2s .c  o m*/
 * @param content String
 * @param fileName String
 * @param destEncoding String
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void writeFile(final String content, final String fileName, final String destEncoding)
        throws FileNotFoundException, IOException {

    File file = null;
    try {
        file = new File(fileName);
        if (file.isFile() == false) {
            throw new IOException("'" + fileName + "' is not a file.");
        }
        if (file.canWrite() == false) {
            throw new IOException("'" + fileName + "' is a read-only file.");
        }
    } finally {
        // we dont have to close File here
    }

    BufferedWriter out = null;
    try {
        FileOutputStream fos = new FileOutputStream(fileName);
        out = new BufferedWriter(new OutputStreamWriter(fos, destEncoding));

        out.write(content);
        out.flush();
    } catch (FileNotFoundException fe) {
        logger.error("Error", fe);
        throw fe;
    } catch (IOException e) {
        logger.error("Error", e);
        throw e;
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
        }
    }
}

From source file:com.clutch.ClutchSync.java

public static void sync(ClutchStats clutchStats) {
    if (thisIsHappening) {
        return;/*from w  ww. j  av  a2s.co m*/
    }
    thisIsHappening = true;
    if (pendingReload) {
        pendingReload = false;
        for (ClutchView clutchView : clutchViews) {
            clutchView.contentChanged();
        }
    }
    ClutchAPIClient.callMethod("sync", null, new ClutchAPIResponseHandler() {
        @Override
        public void onSuccess(JSONObject response) {
            final AssetManager mgr = context.getAssets();

            File parentCacheDir = context.getCacheDir();
            final File tempDir;
            try {
                tempDir = File.createTempFile("clutchtemp", Long.toString(System.nanoTime()), parentCacheDir);
                if (!tempDir.delete()) {
                    Log.e(TAG, "Could not delete temp file: " + tempDir.getAbsolutePath());
                    return;
                }
                if (!tempDir.mkdir()) {
                    Log.e(TAG, "Could not create temp directory: " + tempDir.getAbsolutePath());
                    return;
                }
            } catch (IOException e) {
                Log.e(TAG, "Could not create temp file");
                return;
            }

            File cacheDir = getCacheDir();
            if (cacheDir == null) {
                try {
                    if (!copyAssetDir(mgr, tempDir)) {
                        return;
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Couldn't copy the asset dir files to the temp dir: " + e);
                    return;
                }
            } else {
                try {
                    if (!copyDir(cacheDir, tempDir)) {
                        return;
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Couldn't copy the cache dir files to the temp dir: " + e);
                    return;
                }
            }

            conf = response.optJSONObject("conf");
            String version = "" + conf.optInt("_version");
            newFilesDownloaded = false;
            try {
                JSONCompareResult confCompare = JSONCompare.compareJSON(ClutchConf.getConf(), conf,
                        JSONCompareMode.NON_EXTENSIBLE);
                if (confCompare.failed()) {
                    newFilesDownloaded = true;
                    // This is where in the ObjC version we write out the conf, but I don't think we need to anymore
                }
            } catch (JSONException e1) {
                Log.i(TAG, "Couldn't compare the conf file with the cached conf file: " + e1);
            }

            File cachedFiles = new File(tempDir, "__files.json");
            JSONObject cached = null;
            if (cachedFiles.exists()) {
                StringBuffer strContent = new StringBuffer("");
                try {
                    FileInputStream in = new FileInputStream(cachedFiles);
                    int ch;
                    while ((ch = in.read()) != -1) {
                        strContent.append((char) ch);
                    }
                    in.close();
                    cached = new JSONObject(new JSONTokener(strContent.toString()));
                } catch (IOException e) {
                    Log.e(TAG, "Could not read __files.json from cache file: " + e);
                } catch (JSONException e) {
                    Log.e(TAG, "Could not parse __files.json from cache file: " + e);
                }
            }
            if (cached == null) {
                cached = new JSONObject();
            }

            final JSONObject files = response.optJSONObject("files");
            try {
                JSONCompareResult filesCompare = JSONCompare.compareJSON(cached, files,
                        JSONCompareMode.NON_EXTENSIBLE);
                if (filesCompare.passed()) {
                    complete(tempDir, files);
                    return;
                }
            } catch (JSONException e1) {
                Log.i(TAG, "Couldn't compare the file hash list with the cached file hash list: " + e1);
            }

            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(cachedFiles));
                bw.write(files.toString());
                bw.flush();
                bw.close();
            } catch (FileNotFoundException e) {
            } catch (IOException e) {
            }

            currentFile = 0;
            final int numFiles = files.length();
            Iterator<?> it = files.keys();
            while (it.hasNext()) {
                final String fileName = (String) it.next();
                final String hash = files.optString(fileName);
                final String prevHash = cached.optString(fileName);

                // If they equal, then just continue
                if (hash.equals(prevHash)) {
                    if (++currentFile == numFiles) {
                        complete(tempDir, files);
                        return;
                    }
                    continue;
                }

                // Looks like we've seen a new file, so we should reload when this is all done
                newFilesDownloaded = true;

                // Otherwise we need to download the new file
                ClutchAPIClient.downloadFile(fileName, version, new ClutchAPIDownloadResponseHandler() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            File fullFile = new File(tempDir, fileName);
                            fullFile.getParentFile().mkdirs();
                            fullFile.createNewFile();
                            BufferedWriter bw = new BufferedWriter(new FileWriter(fullFile));
                            bw.write(response);
                            bw.flush();
                            bw.close();
                        } catch (IOException e) {
                            final Writer result = new StringWriter();
                            final PrintWriter printWriter = new PrintWriter(result);
                            e.printStackTrace(printWriter);
                            Log.e(TAG, "Tried, but could not write file: " + fileName + " : " + result);
                        }

                        if (++currentFile == numFiles) {
                            complete(tempDir, files);
                            return;
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String content) {
                        final Writer result = new StringWriter();
                        final PrintWriter printWriter = new PrintWriter(result);
                        e.printStackTrace(printWriter);
                        Log.e(TAG, "Error downloading file from server: " + fileName + " " + result + " "
                                + content);
                        if (++currentFile == numFiles) {
                            complete(tempDir, files);
                            return;
                        }
                    }
                });
            }
        }

        @Override
        public void onFailure(Throwable e, JSONObject errorResponse) {
            Log.e(TAG, "Failed to sync with the Clutch server: " + errorResponse);
        }
    });
    background(clutchStats);
}

From source file:org.matsim.contrib.drt.analysis.DynModeTripsAnalyser.java

public static <T> void collection2Text(Collection<T> c, String filename, String header) {
    BufferedWriter bw = IOUtils.getBufferedWriter(filename);
    try {/*w w w.  jav  a2s.  c om*/
        if (header != null) {
            bw.write(header);
            bw.newLine();
        }
        for (Iterator<T> iterator = c.iterator(); iterator.hasNext();) {

            bw.write(iterator.next().toString());
            bw.newLine();
        }
        bw.flush();
        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:LVCoref.MMAX2.java

/**
 * /*from www.jav  a 2s . co m*/
 * @param filename
 * @param path with trailing "/"
 */
public static void createProject(Document d, String project, String path) {
    String words = path + project + "_words.xml";
    String coref_level = path + project + "_coref_level.xml";
    String sentence_level = path + project + "_sentence_level.xml";
    String project_file = path + project + ".mmax";

    exportWords(d, words);
    exportMentions(d, coref_level);
    exportSentences(d, sentence_level);

    //-----Create project file
    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(project_file), "UTF-8"));
    } catch (java.io.IOException ex) {
        ex.printStackTrace();
    }
    Utils.toWriter(writer,
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<mmax_project>\n" + "<words>" + project
                    + "_words.xml" + "</words>\n" + "<keyactions></keyactions>\n" + "<gestures></gestures>\n"
                    + "</mmax_project>\n");
    try {
        writer.flush();
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(Document.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.mallet.util.MalletUtils.java

public static void writeNewLineToFile(File outputFile) throws IOException {
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outputFile, true)), "UTF-8"));
    bw.write("\n");
    bw.flush();
    bw.close();/*  w  w  w  .jav  a 2  s  .c  o m*/
}

From source file:coolmap.application.io.internal.coolmapobject.InternalCoolMapObjectIO.java

private static void saveCoolMapObjectState(CoolMapObject object, TFile objectFolder) throws Exception {
    TFile stateFolder = new TFile(objectFolder + File.separator + IOTerm.DIR_STATE);

    //Save a state with row, column and selection
    CoolMapState state = CoolMapState.createState("State to save", object, null);

    //Save to JSON
    //save row base nodes
    TFile rowBaseNodeFile = new TFile(
            stateFolder.getAbsolutePath() + File.separator + IOTerm.FILE_STATE_NODE_ROWBASE);
    BufferedWriter rowBaseNodesWriter = new BufferedWriter(
            new OutputStreamWriter(new TFileOutputStream(rowBaseNodeFile)));
    JSONArray rowBaseNodesJSON = nodesToJSON(state.getRowBaseNodes());
    rowBaseNodesJSON.write(rowBaseNodesWriter);
    rowBaseNodesWriter.flush();
    rowBaseNodesWriter.close();/*  w  w w  .  ja  v  a2 s. c o  m*/

    //save row tree nodes
    TFile rowTreeNodeFile = new TFile(
            stateFolder.getAbsolutePath() + File.separator + IOTerm.FILE_STATE_NODE_ROWTREE);
    BufferedWriter rowTreeNodesWriter = new BufferedWriter(
            new OutputStreamWriter(new TFileOutputStream(rowTreeNodeFile)));
    JSONArray rowTreeNodesJSON = nodesToJSON(state.getRowTreeNodes());
    rowTreeNodesJSON.write(rowTreeNodesWriter);
    rowTreeNodesWriter.flush();
    rowTreeNodesWriter.close();

    //save row tree structure
    TFile rowTreeFile = new TFile(stateFolder.getAbsolutePath() + File.separator + IOTerm.FILE_STATE_ROWTREE);
    BufferedWriter rowTreeWriter = new BufferedWriter(
            new OutputStreamWriter(new TFileOutputStream(rowTreeFile)));
    JSONObject rowTreeJSONObject = nodeIDTreeToJSON(state.getRowTreeNodes());
    rowTreeJSONObject.write(rowTreeWriter);
    rowTreeWriter.flush();
    rowTreeWriter.close();

    ////////////////////////////////////////////////////////////////////////
    //seems to be working just fine
    //save column base nodes
    TFile columnBaseNodeFile = new TFile(
            stateFolder.getAbsolutePath() + File.separator + IOTerm.FILE_STATE_NODE_COLUMNBASE);
    BufferedWriter columnBaseNodesWriter = new BufferedWriter(
            new OutputStreamWriter(new TFileOutputStream(columnBaseNodeFile)));
    nodesToJSON(state.getColumnBaseNodes()).write(columnBaseNodesWriter);
    columnBaseNodesWriter.flush();
    columnBaseNodesWriter.close();

    //save column tree nodes
    TFile columnTreeNodeFile = new TFile(
            stateFolder.getAbsolutePath() + File.separator + IOTerm.FILE_STATE_NODE_COLUMNTREE);
    BufferedWriter columnTreeNodesWriter = new BufferedWriter(
            new OutputStreamWriter(new TFileOutputStream(columnTreeNodeFile)));
    nodesToJSON(state.getColumnTreeNodes()).write(columnTreeNodesWriter);
    columnTreeNodesWriter.flush();
    columnTreeNodesWriter.close();

    //save column tree structure
    TFile columnTreeFile = new TFile(
            stateFolder.getAbsolutePath() + File.separator + IOTerm.FILE_STATE_COLUMNTREE);
    BufferedWriter columnTreeWriter = new BufferedWriter(
            new OutputStreamWriter(new TFileOutputStream(columnTreeFile)));
    nodeIDTreeToJSON(state.getColumnTreeNodes()).write(columnTreeWriter);
    columnTreeWriter.flush();
    columnTreeWriter.close();
}

From source file:com.photon.phresco.framework.commons.QualityUtil.java

private static void saveDocument(File file, Document doc) throws Exception {

    TransformerFactory factory1 = TransformerFactory.newInstance();
    Transformer transformer = factory1.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    String content = writer.toString();
    FileWriter fileWriter = new FileWriter(file);
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write(content);/*from  ww w  .j a v  a2 s  .  c  o m*/
    bufferedWriter.flush();
    bufferedWriter.close();
}

From source file:com.almarsoft.GroundhogReader.lib.FSUtils.java

public static void writeReaderToDiskFile(Reader data, String fullPath, String fileName) throws IOException {

    File outDir = new File(fullPath);

    if (!outDir.exists())
        outDir.mkdirs();//from  w ww . ja v  a  2  s  .c om

    BufferedWriter out = null;

    try {
        FileWriter writer = new FileWriter(fullPath + fileName);
        out = new BufferedWriter(writer);

        String readData = null;
        char[] buf = new char[1024];
        int numRead = 0;

        while ((numRead = data.read(buf)) != -1) {
            readData = String.valueOf(buf, 0, numRead);
            out.write(readData);
            buf = new char[1024];
        }

        //out.write(data);
        out.flush();
    } finally {
        if (out != null)
            out.close();
    }
}