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:com.almarsoft.GroundhogReader.lib.ServerManager.java

private static String saveMessageToOutbox(String fullMessage, Context context) {

    String error = null;/* w ww  .  j  a  va  2s. c  om*/

    long outid = DBUtils.insertOfflineSentPost(context);

    String outputDir = UsenetConstants.EXTERNALSTORAGE + "/" + UsenetConstants.APPNAME
            + "/offlinecache/outbox/";
    File outDir = new File(outputDir);
    if (!outDir.exists())
        outDir.mkdirs();

    File outFile = new File(outDir, Long.toString(outid));
    BufferedWriter out = null;

    try {
        FileWriter writer = new FileWriter(outFile);
        out = new BufferedWriter(writer);
        out.write(fullMessage);
        out.flush();
    } catch (IOException e) {
        error = e.getMessage();
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e) {
        }
    }

    return error;
}

From source file:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Copy from file to toFile, expanding properties in the contents
 *
 * @param inputStream  input stream/*from   www  .jav  a  2s  .c  o m*/
 * @param outputStream output stream
 * @param props        properties
 */
private static void expandTemplate(final InputStream inputStream, final OutputStream outputStream,
        final Properties props) throws IOException {

    final BufferedReader read = new BufferedReader(new InputStreamReader(inputStream));
    final BufferedWriter write = new BufferedWriter(new OutputStreamWriter(outputStream));
    String line = read.readLine();
    while (null != line) {
        write.write(expandProperties(props, line));
        write.write(LINESEP);
        line = read.readLine();
    }
    write.flush();
    write.close();
    read.close();
}

From source file:Main.java

public static void writeLifeLogCountInFile(int walking, int running, int vehicle, int bicycle, String filename)
        throws IOException {
    Date date = new Date();
    BufferedWriter writer = null;
    File dir = new File(Environment.getExternalStorageDirectory() + "/LifeLog");
    Log.d("Directory PATH", dir.getAbsolutePath());
    boolean flag = dir.mkdir();
    Log.d("Directory created?", "" + flag);
    File file = new File(dir.getAbsolutePath(), filename);
    if (file.exists() == false) {
        file.createNewFile();//from   w w w . j av a 2 s  .  co  m
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.write("Date,Walking,Running,Bicycle,Vehicle");
        writer.newLine();
        writer.write(date.toString() + "," + walking + "," + running + "," + bicycle + "," + vehicle);
        writer.newLine();
    } else {
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.write(date.toString() + "," + walking + "," + running + "," + bicycle + "," + vehicle);
        writer.newLine();
        Log.d("Appended", "True");
    }
    writer.flush();
    writer.close();

}

From source file:com.bristle.javalib.io.FileUtil.java

/**************************************************************************
* Copy the binary contents of the specified InputStream to the specified
* Writer, up to the specified number of bytes, returning the count of 
* bytes written./*from ww w  .  ja  va2  s. co m*/
*@param  streamIn       InputStream to read from
*@param  writerOut      Writer to write to
*@param  lngMaxBytes    Max number of bytes to copy, or lngNO_MAX_BYTES
*                       for unlimited
*@return                Count of bytes written
*@throws TooManyBytesException
*                       When streamIn contains more than intMaxBytes,
*                       resulting in a partially copied binary stream.
*@throws IOException    When an I/O error occurs reading or writing a
*                       stream or Writer.
**************************************************************************/
public static long copyBinaryStreamToWriter(InputStream streamIn, Writer writerOut, long lngMaxBytes)
        throws TooManyBytesException, IOException {
    // Note: It seems as though this method should be able to call 
    //       copyBinaryStreamToStream() instead of being a nearly 
    //       identical copy of the code, but how to convert a Writer 
    //       to an OutputStream to pass to copyBinaryStreamToStream()?

    // Buffer the input and output for efficiency, to avoid lots of 
    // small I/O operations.
    // Note: Don't call the read() and write() methods that could do it 
    //       all in a single byte-array because we don't want to consume 
    //       that caller-specified amount of memory.  Better to do it
    //       one byte at a time, but with buffering for efficiency.
    BufferedInputStream buffIn = new BufferedInputStream(streamIn);
    BufferedWriter buffOut = new BufferedWriter(writerOut);

    long lngBytesWritten = 0;
    for (int intByte = buffIn.read(); intByte > -1; intByte = buffIn.read()) {
        if (lngMaxBytes != lngNO_MAX_BYTES && lngBytesWritten >= lngMaxBytes) {
            buffOut.flush();
            throw new TooManyBytesException("The input stream contains more than " + lngMaxBytes
                    + " bytes.  Only " + lngBytesWritten + " bytes were written to the " + "writer",
                    lngBytesWritten);
        }
        buffOut.write(intByte);
        lngBytesWritten++;
    }
    buffOut.flush();
    return lngBytesWritten;
}

From source file:Main.java

public static void writeInteractionInFile(Context context, String startTime, String endTime, long duration,
        String filename) throws IOException, Exception {

    BufferedWriter writer = null;
    //String path="sdcard/LifeTracker/lifetracker.csv";
    File dir = new File("sdcard/SleepLog");
    boolean flag = dir.mkdir();
    //Log.d("Directory created?",""+flag);
    File file = new File(dir.getAbsolutePath(), filename);
    if (file.exists() == false) {
        //                  Intent service = new Intent(context,DataBaseService.class);
        //                  context.startService(service);
        file.createNewFile();//from   w ww  . j a  v  a  2 s.  c  om
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.write("Start Time,End Time,Duration");
        writer.newLine();
        writer.write(startTime + "," + endTime + "," + duration);
    } else {
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.newLine();
        writer.write(startTime + "," + endTime + "," + duration);
    }
    Log.d("Appended", "True");
    writer.flush();
    writer.close();

}

From source file:URLEncoder.java

public static String encode(String s, String enc) throws UnsupportedEncodingException {
    if (!needsEncoding(s)) {
        return s;
    }//from   w  w w .j a v a2s. com

    int length = s.length();

    StringBuffer out = new StringBuffer(length);

    ByteArrayOutputStream buf = new ByteArrayOutputStream(10); // why 10?
    // w3c says
    // so.

    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(buf, enc));

    for (int i = 0; i < length; i++) {
        int c = (int) s.charAt(i);
        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == ' ') {
            if (c == ' ') {
                c = '+';
            }

            toHex(out, buf.toByteArray());
            buf.reset();

            out.append((char) c);
        } else {
            try {
                writer.write(c);

                if (c >= 0xD800 && c <= 0xDBFF && i < length - 1) {
                    int d = (int) s.charAt(i + 1);
                    if (d >= 0xDC00 && d <= 0xDFFF) {
                        writer.write(d);
                        i++;
                    }
                }

                writer.flush();
            } catch (IOException ex) {
                throw new IllegalArgumentException(s);
            }
        }
    }
    try {
        writer.close();
    } catch (IOException ioe) {
        // Ignore exceptions on close.
    }

    toHex(out, buf.toByteArray());

    return out.toString();
}

From source file:jeplus.INSELWinTools.java

/**
 * Call INSEL executable file to run the simulation
 * @param config INSEL Configuration/*from  w  ww  . j a v  a 2s .co m*/
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param useReadVars Whether or not to use readvars after simulation
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runINSEL(INSELConfig config, String WorkDir, String modelfile) {

    int ExitValue = -99;

    try {
        // Trace simulation time
        Date start = new Date();

        // Run EnergyPlus executable
        String CmdLine = config.getResolvedInselEXEC() + " " + modelfile;
        Process EPProc = Runtime.getRuntime().exec(CmdLine, null, new File(WorkDir));

        BufferedReader ins = new BufferedReader(new InputStreamReader(EPProc.getInputStream()));
        // Use console output as the report file
        BufferedWriter outs = new BufferedWriter(new FileWriter(WorkDir + config.ScreenFile, false));
        outs.newLine();
        outs.write("Calling insel.exe - " + (new SimpleDateFormat()).format(start));
        outs.newLine();
        outs.write("Command line: " + WorkDir + ">" + CmdLine);
        outs.newLine();

        int res = ins.read();
        while (res != -1) {
            outs.write(res);
            res = ins.read();
        }
        ins.close();
        outs.newLine();
        outs.write("Simulation time: " + Long.toString((new Date().getTime() - start.getTime()) / 1000)
                + " seconds");
        outs.flush();
        outs.close();

        EPProc.waitFor();
        ExitValue = EPProc.exitValue();
    } catch (IOException | InterruptedException e) {
        logger.error("Exception during INSEL execution.", e);
    }

    // Return Radiance exit value
    return ExitValue;
}

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

public static void outputPredictions(TransducerEvaluator eval, File fileTest, File filePredictions,
        String predictionClassLabelName) throws IOException {
    ArrayList<String> predictedLabels = ((PerClassEvaluator) eval).getPredictedLabels();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(new GZIPInputStream(new FileInputStream(fileTest)), "UTF-8"));
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(filePredictions)), "UTF-8"));
    String line;//from w  w w .j  av a2  s. co  m
    boolean header = false;
    int i = 0;
    while ((line = br.readLine()) != null) {
        if (!header) {
            bw.write(line + " " + predictionClassLabelName);
            bw.flush();
            header = true;
            continue;
        }
        if (!line.isEmpty()) {
            bw.write("\n" + line + " " + predictedLabels.get(i++));
            bw.flush();
        } else {
            bw.write("\n");
            bw.flush();
        }
    }
    br.close();
    bw.close();
}

From source file:com.piaoyou.util.FileUtil.java

/**
 * Write content to a fileName with the destEncoding
 *
 * @param content String/*  w w w  .ja v a2 s . c  om*/
 * @param fileName String
 * @param destEncoding String
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void writeFile(String content, String fileName, 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 don't 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) {
        log.error("Error", fe);
        throw fe;
    } catch (IOException e) {
        log.error("Error", e);
        throw e;
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException ex) {
        }
    }
}

From source file:com.tencent.wetest.common.util.ReportUtil.java

public static void delRecord(String name) {

    path = WTApplication.getContext().getFilesDir().getPath();

    File f = new File(path + "/wtIndex");
    String fileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/wetest";
    File tmp = new File(fileDir + "/" + name);
    if (tmp.exists()) {
        tmp.delete();// w  ww .j a  v  a2s.co  m
    }
    List<String> content = new ArrayList<String>();

    if (f.exists() && f.isFile()) {
        try {
            BufferedReader indexreader = new BufferedReader(new FileReader(f));
            String br = "";
            while ((br = indexreader.readLine()) != null) {
                if (!br.split("/")[0].equals(name))
                    content.add(br);
            }

            indexreader.close();
            if (content.size() != 0) {
                BufferedWriter indexwriter = new BufferedWriter(new FileWriter(f, false));
                int i = 0;
                for (String temp : content) {

                    if (i == content.size() - 1)
                        indexwriter.write(temp);
                    else
                        indexwriter.write(temp + "\t\n");
                    i++;
                }

                indexwriter.flush();
                indexwriter.close();

            } else {

                f.delete();

            }

        } catch (Exception e) {
            Logger.error("delException:" + e.toString());
            e.printStackTrace();
        }

    }
}