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:TalkServerThread.java

public void writeToStream(String string, BufferedWriter stream) {
    if (DEBUG) {//from w w w  . java2  s . c o  m
        System.out.println("TalkServer about to forward data: "
                           + string);
    }

    try { 
        stream.write(string);
   stream.newLine();
        stream.flush();
        if (DEBUG) {
            System.out.println("TalkServer forwarded string.");
        }
    } catch (IOException e) {
        System.err.println("TalkServer failed to forward string:");
        e.printStackTrace();
        return;
    } catch (NullPointerException e) {
        System.err.println("TalkServer can't forward string "
                           + "since output stream is null.");
        return;
    }
}

From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java

/**
 * Does the work of writing the given object update to the feed file
 * /*  w ww.  j ava2 s.  c  o m*/
 * @param action what happened
 * @param object the object that was changed
 * @should initialize header file
 * @should change updated time in existing header file
 * @should prepend valid entry to entries file
 */
protected static synchronized void writeToFeed(String action, OpenmrsObject object) {

    // get handle on file for entries
    File atomfile = getFeedEntriesFile();

    // write action/change to file
    String entry = getEntry(action, object);
    // prepend given entry string to the beginning of atom file
    BufferedWriter out = null;
    FileInputStream source = null;
    FileOutputStream destination = null;
    File temporaryAtomFile = null;
    try {

        // create hidden temporary atom file within atom feeds  
        // directory to write new feed entry to
        if (!atomfile.exists()) {
            out = new BufferedWriter(new FileWriter(atomfile, Boolean.TRUE));
            out.write(entry);
            out.newLine();
        } else {
            temporaryAtomFile = new File(atomfile.getParent(), ".".concat(atomfile.getName()));
            out = new BufferedWriter(new FileWriter(temporaryAtomFile, Boolean.TRUE));
            out.write(entry);
            out.newLine();
            // copy existing atom feed entries from current atom feed file
            // to temporary file
            BufferedReader br = new BufferedReader(new FileReader(atomfile));
            while ((entry = br.readLine()) != null) {
                out.write(entry);
                out.newLine();
            }
            out.flush();
            IOUtils.closeQuietly(out);

            // get rid of old feed entries file by swap it's content with new one
            source = new FileInputStream(temporaryAtomFile);
            destination = new FileOutputStream(atomfile);
            IOUtils.copy(source, destination);
        }
    } catch (IOException e) {
        log.error("Unable to write entry to the feed entries file, because of error:", e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(source);
        IOUtils.closeQuietly(destination);
        FileUtils.deleteQuietly(temporaryAtomFile);
    }

    // get handle on header file
    File atomheaderfile = getFeedHeaderFile();

    // re-/creates the header and/or updates the "last updated" time to now
    // the entire file doesn't always need rewritten for every entry,
    // but its not that large, so we're not losing many cpu cycles
    // TODO: look into only changing the "updated" element to reduce cpu
    // usage -- ATOM-4        
    updateFeedFileHeader(atomheaderfile, atomfile.length());
}

From source file:com.all.client.util.FileUtil.java

public void writeLinesToFile(List<String> stringList, String path) {
    FileWriter fileWriter = null;
    BufferedWriter bw = null;
    try {// w  w  w  .j a va2  s .c o m
        fileWriter = new FileWriter(path);
        bw = new BufferedWriter(fileWriter);

        for (String line : stringList) {
            bw.write(line);
            bw.newLine();
        }
        bw.flush();

    } catch (IOException e) {
        LOG.error(e, e);
    } finally {
        closeWriter(bw);
        closeWriter(fileWriter);
    }
}

From source file:ch.vorburger.webdriver.reporting.TestCaseReportWriter.java

public void writeToFile(String message) {
    // TODO Use something in org.apache.commons.io.FileUtils which does this..
    if (message.indexOf(END_TEST) > 0) {
        BufferedWriter bufferedWriter = null;
        try {//from  w ww . j a  v  a  2  s .co  m
            bufferedWriter = new BufferedWriter(new FileWriter(getLogFile().getPath(), true));
            bufferedWriter.newLine();
            bufferedWriter.append(message);
        } catch (IOException e) {
            // e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                // ex.printStackTrace();
            }
        }
    }
}

From source file:org.balloon_project.overflight.task.indexing.IndexingTask.java

private void dumpIndexedTriples(List<Triple> results) throws IOException {
    Stopwatch storeTimer = Stopwatch.createStarted();

    if (results.size() > 0) {
        BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));

        try {//from   w ww .j  av  a 2  s  . c o m
            for (Triple triple : results) {
                StringBuilder sb = new StringBuilder();
                sb.append("<").append(triple.getSubject()).append("> <")
                        .append(triple.getRelEntity().getPredicate()).append("> <").append(triple.getObject())
                        .append(">.\n");
                writer.append(sb.toString());
            }
        } finally {
            writer.flush();
            writer.close();
        }
    }

    logger.debug(this.endpoint.getEndpointID() + ": Intermediate result persisted (Size = " + results.size()
            + ") Continue query process" + " (save duration: "
            + storeTimer.stop().elapsed(TimeUnit.MILLISECONDS) + " ms) predicate " + relEntity.getPredicate());
}

From source file:com.devilyang.musicstation.cache.ACache.java

/**
 * ? String?  /*  w ww  .j a va 2 s. c om*/
 * 
 * @param key
 *            ?key
 * @param value
 *            ?String?
 */
public void put(String key, String value) {
    File file = mCacheManager.newFile(key);
    BufferedWriter out = null;
    try {
        out = new BufferedWriter(new FileWriter(file), 1024);
        out.write(value);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mCacheManager.put(file);
    }
}

From source file:edu.indiana.soic.ts.mapreduce.pwd.PairWiseDistance.java

private void partitionData(String sequenceFile, int noOfSequences, int blockSize, FileSystem fs,
        int noOfDivisions, Configuration jobConf, Path inputDir)
        throws FileNotFoundException, IOException, URISyntaxException {
    // Break the sequences file in to parts based on the block size. Stores
    // the parts in HDFS and add them to the Hadoop distributed cache.
    Path path = new Path(sequenceFile);
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fs.open(path)));

    LOG.info("noOfDivisions : " + noOfDivisions);
    LOG.info("blockSize : " + blockSize);
    for (int partNo = 0; partNo < noOfDivisions; partNo++) {
        //// w w w.  ja v a 2 s. c  o  m
        String filePartName = Constants.HDFS_SEQ_FILENAME + "_" + partNo;
        Path inputFilePart = new Path(inputDir, filePartName);
        OutputStream partOutStream = fs.create(inputFilePart);
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(partOutStream));

        for (int sequenceIndex = 0; ((sequenceIndex < blockSize)
                & (sequenceIndex + (partNo * blockSize) < noOfSequences)); sequenceIndex++) {
            String line;
            line = bufferedReader.readLine();
            if (line == null) {
                throw new IOException("Cannot read the sequence from input file.");
            }
            // write the sequence name
            bufferedWriter.write(line);
            bufferedWriter.newLine();
        }
        bufferedWriter.flush();
        bufferedWriter.close();
        // Adding the sequences file to Hadoop cache
        URI cFileURI = new URI(inputFilePart.toUri() + "#" + filePartName);
        DistributedCache.addCacheFile(cFileURI, jobConf);
        DistributedCache.createSymlink(jobConf);
    }
}

From source file:gtu._work.ui.LoadJspFetchJavascriptUI.java

private void executeBtnActionPerformed(ActionEvent evt) {
    try {//from  ww w .j a v a 2s  .  co  m
        String subName = Validate.notBlank(subNameText.getText());
        if (StringUtils.isNotBlank(tagPatternText.getText())) {
            String startP = "\\<" + tagPatternText.getText();
            String endP = "\\<\\/" + tagPatternText.getText() + "\\>";
            javascriptStart = Pattern.compile(startP, Pattern.CASE_INSENSITIVE);
            javascriptEnd = Pattern.compile(endP, Pattern.CASE_INSENSITIVE);
            JCommonUtil._jOptionPane_showMessageDialog_info(
                    String.format("tagPattern:\nstart:\n%send:\n%s", startP, endP));
        }

        long startTime = System.currentTimeMillis();

        File file = JCommonUtil.filePathCheck(filePathText.getText(), "?", false);
        List<File> fileList = new ArrayList<File>();
        if (file.isFile()) {
            fileList.add(file);
        } else {
            if (subName.startsWith(".")) {
                subName = subName.substring(1);
            }
            FileUtil.searchFilefind(file, ".*\\." + subName + "$", fileList);
        }
        File outputFile = new File(FileUtil.DESKTOP_PATH,
                "javascript_" + DateUtil.getCurrentDateTime(false) + ".txt");
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outputFile), "utf8"));
        for (File f : fileList) {
            String content = writeScript(f);
            if (content.length() > 0) {
                writer.write(
                        "#start#" + f.getAbsolutePath() + "#==============================================");
                writer.newLine();
                writer.write(content);
                writer.write(
                        "#end  #" + f.getAbsolutePath() + "#==============================================");
                writer.newLine();
            }
        }
        writer.flush();
        writer.close();

        long duringTime = System.currentTimeMillis() - startTime;

        JCommonUtil._jOptionPane_showMessageDialog_info(
                "?,:" + fileList.size() + "\n:" + duringTime);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:com.tek42.perforce.parse.AbstractPerforceTemplate.java

/**
 * Read the last line of output which should be the ticket.
 * //from   ww  w. j  a va 2s  .com
 * @param p4Exe the perforce executable with or without full path information
 * @return the p4 ticket
 * @throws IOException if an I/O error prevents this from working
 * @throws PerforceException if the execution of the p4Exe fails
 */
private String p4Login(String p4Exe) throws IOException, PerforceException {
    Executor login = depot.getExecFactory().newExecutor();
    login.exec(new String[] { p4Exe, "login", "-a", "-p" });

    try {
        // "echo" the password for the p4 process to read
        BufferedWriter writer = login.getWriter();
        try {
            writer.write(depot.getPassword() + "\n");
        } finally {
            // help the writer move the data
            writer.flush();
        }
        // read the ticket from the output
        String ticket = null;
        BufferedReader reader = login.getReader();
        String line;
        // The line matching ^[0-9A-F]{32}$ will be the ticket
        while ((line = reader.readLine()) != null) {
            int error = checkAuthnErrors(line);
            if (error != -1)
                throw new PerforceException("Login attempt failed: " + line);
            if (line.trim().matches("^[0-9A-F]{32}$"))
                ticket = line;
        }

        return ticket;
    } finally {
        login.close();
    }
}

From source file:com.github.tteofili.calabrize.impl.RNN.java

public void serialize(String prefix) throws IOException {
    BufferedWriter bufferedWriter = new BufferedWriter(
            new FileWriter(new File(prefix + new Date().toString() + ".txt")));
    bufferedWriter.write("wxh");
    bufferedWriter.write(wxh.toString());
    bufferedWriter.write("whh");
    bufferedWriter.write(whh.toString());
    bufferedWriter.write("why");
    bufferedWriter.write(why.toString());
    bufferedWriter.write("bh");
    bufferedWriter.write(bh.toString());
    bufferedWriter.write("by");
    bufferedWriter.write(by.toString());
    bufferedWriter.flush();
    bufferedWriter.close();//from w ww. j  a v a  2  s.  c o  m
}