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:ir.pooyahfp.matrixcli.ProgramTest.java

@Test
public void testLoadCommandFile() throws Exception {
    String path = "test.txt";
    BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
    writer.write("matrix x 3 3");
    writer.newLine();// www .  j av a2  s . co  m
    writer.write("show x");
    writer.flush();
    writer.close();

    program.loadCommandFile(path);
}

From source file:com.vmware.bdd.utils.CommonUtil.java

public static void prettyOutputStrings(List<Object> objs, String fileName, String delimeter) throws Exception {
    StringBuffer buff = new StringBuffer();
    if (isBlank(delimeter)) {
        delimeter = System.lineSeparator();
    }// w ww  . j  av a2s.  c o m

    for (Object obj : objs) {
        if (obj != null) {
            String str = obj.toString();
            if (!isBlank(str)) {
                buff.append(str).append(delimeter);
            }
        }
    }
    if (buff.length() > 0) {
        buff.delete(buff.length() - delimeter.length(), buff.length());
    }

    OutputStream out = null;
    BufferedWriter bw = null;
    try {
        if (!isBlank(fileName)) {
            out = new FileOutputStream(fileName);
        } else {
            out = System.out;
        }
        bw = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        bw.write(buff.toString());
        if (!isBlank(fileName)) {
            // [Bug 1406542] always append a newline at the end of the file
            bw.newLine();
        }
        bw.flush();
    } finally {
        if (bw != null && out != null && !(out instanceof PrintStream)) {
            bw.close();
            out.close();
        }
    }
}

From source file:tomekkup.helenos.web.servlet.view.CsvView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + (String) model.get("key") + "_" + (String) model.get("key") + ".csv\"");
    BufferedWriter writer = new BufferedWriter(response.getWriter());

    //myDbData = (Whatever) modelMap.get("modelKey");
    //some kind of loop {writer.write(myDbData csv row); writer.newLine(); }
    writer.flush();
    writer.close();/*from  w  w w  .  j  av  a2s .c om*/
}

From source file:com.vmanolache.mqttpolling.Polling.java

private void sendPost() throws UnsupportedEncodingException, JSONException {
    try {/*from  w  w w  .  ja  v a 2 s  . c  o  m*/
        String url = "http://localhost:8080/notifications";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST");

        /**
         * POSTing *
         */
        OutputStream os = connection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQuery()); // should be fine if my getQuery is encoded right yes?
        writer.flush();
        writer.close();
        os.close();
        connection.connect();

        int status = connection.getResponseCode();
        System.out.println(status);
    } catch (IOException ex) {
        Logger.getLogger(Polling.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:model.settings.ReadSettings.java

/**
 * Set up paint as program in OSX.//from   w w  w.ja v a2  s .  co m
 */
private static void installOSX() {

    try {

        final String name = "paint";
        final String app_name = "Paint.app";
        /*
         * STEP 1:   Create files and folders for the info.plist
         */
        final String filePath = "/Applications/" + app_name + "/Contents/";
        final String fileName = "Info.plist";
        final String fileContent = "" + "<dict>\n" + "    <key>CFBundleTypeExtensions</key>\n" + "    <array>\n"
                + "        <string>jpeg</string>\n" + "        <string>png</string>\n"
                + "        <string>gif</string>\n" + "        <string>pic</string>\n" + "    </array>\n"
                + "</dict>";

        FileWriter fw;
        // create necessary directories
        File p = new File(filePath);
        p.mkdirs();

        //TODO: this is just a debug parameter
        boolean installed = new File(filePath + fileName).exists();
        if (!installed) {

            // Create info.plist
            fw = new FileWriter(filePath + fileName);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fileContent);
            bw.flush();
            bw.close();
            fw.close();
        }

        /*
         * STEP 2:   Create (executable) file which is called if the 
         *          application is run.
         */
        final String app_folder_path = filePath + "MacOS/";
        final String app_file_path = app_folder_path + name;
        new File(app_folder_path).mkdirs();
        String orig_jar_file = "";
        orig_jar_file = URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(),
                "UTF-8");

        // if Eclipse on-the-fly-compiling
        final String eclipseSubstring = "target/classes/";
        if (orig_jar_file.endsWith(eclipseSubstring)) {
            orig_jar_file = orig_jar_file.substring(0, orig_jar_file.length() - eclipseSubstring.length());

        }
        orig_jar_file += "paint.jar";

        final String jar_file_path = app_file_path + ".jar";
        final String content = "#!/bin/bash\n" + "echo $1\n" + "echo $2\n" + "echo $3\n" + "java -jar "
                + jar_file_path + " $@$0$1";

        // Create application file
        FileWriter fw2 = new FileWriter(app_file_path);
        BufferedWriter bw_2 = new BufferedWriter(fw2);
        bw_2.write(content);
        bw_2.flush();
        bw_2.close();
        fw2.close();

        // Make the file executable

        final String command0 = "chmod a+x " + app_file_path;
        String ret = Util.executeCommandLinux(command0);

        /*
         * Step 3:   Copy .jar file to the destination.
         */

        final String command1 = "cp " + orig_jar_file + " " + jar_file_path;
        String ret1 = Util.executeCommandLinux(command1);

        if (!installed) {

            final String command2 = "/System/Library/Frameworks/CoreServices.framework/Versions/"
                    + "A/Frameworks/LaunchServices.framework/Versions/A/Support/"
                    + "lsregister -f /Applications/" + app_name + "/";
            String ret2 = Util.executeCommandLinux(command2);

            final String command3 = "killall Finder";
            String ret3 = Util.executeCommandLinux(command3);

            String s = "Operation log:\n";
            System.out.println(s);
            System.out.println(ret + "\n" + ret1 + "\n" + ret2 + "\n" + ret3);

        }

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

From source file:org.apache.hadoop.gateway.jetty.SslSocketTest.java

@Ignore
@Test//from www .  j a v a2  s  .  c om
public void testSsl() throws IOException, InterruptedException {
    SslServer server = new SslServer();
    Thread thread = new Thread(server);
    thread.start();
    server.waitUntilReady();

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    SSLSocketFactory sslsocketfactory = SSLSocketFactory.getSocketFactory();
    SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(params);

    sslsocket.connect(new InetSocketAddress("localhost", 9999));

    OutputStream outputstream = sslsocket.getOutputStream();
    OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
    BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);

    bufferedwriter.write("HELLO\n");
    bufferedwriter.flush();
}

From source file:au.org.ala.delta.intkey.model.StartupUtils.java

/**
 * Save a copy of a dataset that was opened from a remote location
 * /*www .j  a va  2 s  .c  o  m*/
 * @param context
 *            Intkey context
 * @param saveDir
 *            Directory in which to save a copy of the dataset
 * @return A copy of the JNLP-style dataset startup file to use to open the
 *         saved copy of the dataset.
 * @throws IOException
 *             If saving to disk failed.
 */
public static File saveRemoteDataset(IntkeyContext context, File saveDir) throws IOException {
    StartupFileData startupFileData = context.getStartupFileData();
    File datasetZip = startupFileData.getDataFileLocalCopy();

    // Copy the zipped dataset as downloaded from the web
    // FileUtils.copyFileToDirectory(datasetZip, saveDir);

    // Copy the zipped dataset as downloaded from the web
    // Use utility method to avoid overwriting existing files with the same
    // name
    File copyZipFile = Utils.getSaveFileForDirectory(saveDir, datasetZip.getName());
    FileUtils.copyFile(datasetZip, copyZipFile);

    // Write a new .ink file
    // Use utility method to avoid overwriting existing files with the same
    // name
    File newInkFile = Utils.getSaveFileForDirectory(saveDir,
            FilenameUtils.getName(startupFileData.getInkFileLocation().getFile()));

    FileWriter fw = new FileWriter(newInkFile);
    BufferedWriter bufFW = new BufferedWriter(fw);

    bufFW.append(INIT_FILE_INK_FILE_KEYWORD);
    bufFW.append("=");
    bufFW.append(newInkFile.toURI().toURL().toString());
    bufFW.append("\n");

    bufFW.append(INIT_FILE_DATA_FILE_KEYWORD);
    bufFW.append("=");
    bufFW.append(copyZipFile.toURI().toURL().toString());
    bufFW.append("\n");

    bufFW.append(INIT_FILE_INITIALIZATION_FILE_KEYWORD);
    bufFW.append("=");
    bufFW.append(startupFileData.getInitializationFileLocation());
    bufFW.append("\n");

    String imagePath = startupFileData.getImagePath();
    if (imagePath != null) {
        bufFW.append(INIT_FILE_IMAGE_PATH_KEYWORD);
        bufFW.append("=");
        bufFW.append(imagePath);
        bufFW.append("\n");
    }

    String infoPath = startupFileData.getInfoPath();
    if (infoPath != null) {
        bufFW.append(INIT_FILE_INFO_PATH_KEYWORD);
        bufFW.append("=");
        bufFW.append(infoPath);
        bufFW.append("\n");
    }

    bufFW.flush();
    bufFW.close();

    return newInkFile;
}

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

public static void updateRecord(File f, String name, String record) {

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

    List<String> content = new ArrayList<String>();

    if (f.exists() && f.isFile()) {

        try {/*from  w w w.  j  av a2s . c o m*/

            String br = "";
            boolean hasRecord = false;
            BufferedReader indexreader = new BufferedReader(new FileReader(f));

            while ((br = indexreader.readLine()) != null) {
                if (br.split("/")[0].equals(name)) {

                    content.add(record);
                    hasRecord = true;
                } else {
                    content.add(br);

                }
            }

            if (!hasRecord)
                content.add(record);

            indexreader.close();

            BufferedWriter indexwriter = new BufferedWriter(new FileWriter(f, false));

            if (content.size() == 0) {

                indexwriter.write(record);

            } else {
                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();

        } catch (Exception e) {

            Logger.error("updateRecord exception : " + e.toString());
            e.printStackTrace();
        }

    }
}

From source file:com.sir_m2x.messenger.utils.CustomExceptionHandler.java

private void writeToFile(final String stacktrace, final String filename) {
    try {/*from w ww .  j  a v a 2  s  .  c om*/
        File f = new File(this.localPath + "/");
        if (!f.exists())
            f.mkdir();
        BufferedWriter bos = new BufferedWriter(new FileWriter(this.localPath + "/" + filename));
        bos.write(stacktrace);
        bos.flush();
        bos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.uwsoft.editor.controlles.handlers.CustomExceptionHandler.java

private void writeToFile(String stacktrace, String filename) {
    try {/*w  ww  .  j a  v  a 2s  .  c om*/
        //String localPath = DataManager.getMyDocumentsLocation();
        String localPath = DataManager.getInstance().getRootPath();
        System.out.println(localPath + File.separator + filename);
        BufferedWriter bos = new BufferedWriter(new FileWriter(localPath + File.separator + filename));
        bos.write(stacktrace);
        bos.flush();
        bos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}