Example usage for java.io FileWriter flush

List of usage examples for java.io FileWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:controllers.ControllerServlet.java

private void save() {
    String filePath;//from ww  w. jav  a  2 s.  c  o  m
    filePath = "/Users/ivan/Desktop/ufns.json";
    JSONObject obj = UFNS.getInstance().getJSONObject();
    try {

        FileWriter file = new FileWriter(filePath);
        file.write(obj.toJSONString());
        file.flush();
        file.close();

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

}

From source file:com.seanmadden.net.fast.FastInterpretype.java

public FastInterpretype() {

    BufferedReader reader;/*from  w  w  w .  ja  v  a 2  s .co  m*/
    try {
        reader = new BufferedReader(new FileReader(filename));
        String line = "", jsonData = "";
        while ((line = reader.readLine()) != null) {
            jsonData += line;
        }
        config = new JSONObject(jsonData);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        System.out.println("Configuration not found!  Preloading settings.");
        try {
            config.put("SerialPort", "COM1");
            config.put("SerialBaud", 19200);
            config.put("SerialParity", 0);
            config.put("SerialBits", 8);
            config.put("SerialStopBits", 1);
            config.put("StringBreakLength", 50);
            config.put("OperatorName", "Operator");
            FileWriter writer = new FileWriter(filename);
            config.write(writer);
            writer.flush();
            writer.close();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    si = new SerialInterface(config);
    si.open();
    si.addObserver(this);
    mw = new MainWindow(this);
    si.sendRawDataToPort(DataPacket.generateClearConvoPayload());
    String username = JOptionPane.showInputDialog("What is your name?");
    si.sendRawDataToPort(DataPacket.generateSignedOnPayload(username));
    mw.acceptText(username + " (you) has signed on.\n");
    mw.setLocalUserName(username);
    try {
        config.put("OperatorName", username);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    mw.validate();
    mw.setVisible(true);
}

From source file:com.cyberway.issue.crawler.scope.SeedCachingScopeTest.java

public void testNoScheme() throws IOException {
    final String NOSCHEME = "x.y.z";
    FileWriter fw = new FileWriter(this.seedsfile, true);
    // Write to new (last) line the URL.
    fw.write("\n");
    fw.write(NOSCHEME);/*from w w  w  .  j a v a 2  s  .  com*/
    fw.flush();
    fw.close();
    boolean found = false;
    SeedCachingScope sl = new UnitTestSeedCachingScope(seedsfile);
    for (Iterator i = sl.seedsIterator(); i.hasNext();) {
        UURI uuri = (UURI) i.next();
        if (uuri.getHost() == null) {
            continue;
        }
        if (uuri.getHost().equals(NOSCHEME)) {
            found = true;
            break;
        }
    }
    assertTrue("Did not find " + NOSCHEME, found);
}

From source file:com.bingzer.android.driven.Credential.java

public void save(String name) {
    FileWriter writer = null;
    try {/*from  www . ja  va 2s  .  c o m*/
        writer = new FileWriter(getCredentialFile(name));
        writer.write(toString());
        writer.flush();
        writer.close();
    } catch (IOException e) {
        Log.e(TAG, "Failed to save credentials to file", e);
    } finally {
        safeClose(writer);
    }
}

From source file:com.seanmadden.net.fast.FastInterpretype.java

public void configEditWindow() {
    final JFrame frame = new JFrame();
    final Vector<ConfigOption> components = new Vector<ConfigOption>();
    JPanel buttons = new JPanel(new GridLayout(1, 2));
    JButton ok = new JButton("Save");
    ok.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            for (ConfigOption config : components) {
                config.actionPerformed(null);
            }/*from w w w . j a v a2 s  . c  o  m*/
            frame.dispose();
            try {
                FileWriter writer = new FileWriter(filename);
                config.write(writer);
                writer.flush();
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }

    });
    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            frame.dispose();
        }
    });
    buttons.add(ok);
    buttons.add(cancel);
    Iterator<String> rator = config.keys();
    int size = 0;
    try {
        while (rator.hasNext()) {
            String key = (String) rator.next();
            ConfigOption config = new ConfigOption(key, this.config.getString(key));
            frame.add(config);
            components.add(config);
            ++size;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    frame.setLayout(new GridLayout(size + 1, 1));
    frame.add(buttons);
    frame.setSize(300, 400);
    frame.pack();
    frame.setVisible(true);
}

From source file:se.vgregion.portal.cs.util.CryptoUtilImpl.java

/**
 * Encrypt a value and generate a keyfile. if the keyfile is not found then a new one is created
 * //from   w  w w .j  a v a 2s  .c o m
 * @param value
 *            - value to be encrypted
 * @throws GeneralSecurityException
 *             - security exception
 * @return Encrypted value
 */
@Override
public String encrypt(String value) throws GeneralSecurityException {
    if (!keyFile.exists()) {
        KeyGenerator keyGen = KeyGenerator.getInstance(AES);
        keyGen.init(KEY_SIZE);
        SecretKey sk = keyGen.generateKey();
        FileWriter fw = null;
        try {
            fw = new FileWriter(keyFile);
            fw.write(byteArrayToHexString(sk.getEncoded()));
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    SecretKeySpec sks = getSecretKeySpec();

    Cipher cipher = Cipher.getInstance(AES);
    cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
    byte[] encrypted = cipher.doFinal(value.getBytes());
    return byteArrayToHexString(encrypted);
}

From source file:gov.nih.nci.cagrid.caarray.client.CaArray2xGrid.java

protected synchronized long printResults(CQLQueryResults results, String outFileName) {
    try {/*from   www. ja  va 2  s  .  c om*/
        // StringWriter w = new StringWriter();
        String fileName = "test/logs/" + outFileName;
        new File(fileName).delete();
        FileWriter w = new FileWriter(fileName);
        Utils.serializeObject(results,
                new QName("http://CQL.caBIG/1/gov.nih.nci.cagrid.CQLResultSet", "CQLResultSet"), w);
        w.flush();
        w.close();
        long fileSize = new File(fileName).length();

        LOG.debug("... done printing results to : " + outFileName + " size=" + fileSize + " bytes");
        return fileSize;
    } catch (Exception ex) {
        throw new RuntimeException("Error printing results: " + ex.getMessage(), ex);
    }
}

From source file:fr.mcc.ginco.services.ThesaurusServiceImpl.java

@Transactional(readOnly = false)
@Override// w w  w  .j a v  a2  s.c  om
public Thesaurus archiveThesaurus(Thesaurus thesaurus) {

    String fileContent = gincoThesaurusExportService.getThesaurusExport(thesaurus);
    File ready = new File(archivePath + thesaurus.getTitle().replaceAll("[^a-zA-Z0-9\\._]+", "_") + "_"
            + DateUtil.toString(DateUtil.nowDate()).replaceAll(" ", "_").replaceAll(":", "_") + ".xml");
    try {
        File checkPath = new File(archivePath);
        if (!checkPath.exists()) {
            FileUtils.forceMkdir(checkPath);
        }
        FileWriter writer = new FileWriter(ready);
        writer.write(fileContent);
        writer.flush();
        writer.close();

    } catch (IOException e) {
        throw new TechnicalException("Error writing file to path : " + publishPath, e);
    }

    thesaurus.setArchived(Boolean.TRUE);
    return thesaurusDAO.update(thesaurus);
}

From source file:com.verigreen.collector.jobs.HistoryCleanerJob.java

private void updateHistory(Map<String, List<JSONObject>> newHistory) {
    FileWriter file;
    VerigreenNeededLogic.history = newHistory;
    try {// w  ww  . ja  va2  s  .com
        file = new FileWriter(System.getenv("VG_HOME") + "//history.json");
        JSONObject history = new JSONObject(VerigreenNeededLogic.history);
        file.write(history.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        VerigreenLogger.get().error(getClass().getName(), RuntimeUtils.getCurrentMethodName(),
                String.format("Failed updating json file: " + System.getenv("VG_HOME") + "\\history.json", e));
    }
}

From source file:net.sf.ginp.commands.UploadConfig.java

/**
 *  Handle admin request to upload an new configuration file.
 *
 * @param  model   Description of the Parameter
 * @param  params  Description of the Parameter
 *//*w  w  w.java  2 s.  c  o m*/
public final void action(final GinpModel model, final Vector params) {
    // Check we do not have a state of bad config.
    if (Configuration.configOK()) {
        return;
    }

    File confFile = new File(Configuration.getConfigfilelocation());

    // check that file is not there.
    if (confFile.exists()) {
        log.error("Config File there but NOT OK.  Fix it or remove it.");

        return;
    }

    for (int i = 0; i < params.size(); i++) {
        CommandParameter param = (CommandParameter) params.get(i);
        log.debug(param.getName() + " = " + param.getValue());

        if (param.getName().equals("configfile")) {
            try {
                InputStream is = (InputStream) param.getObject();
                InputStreamReader isr = new InputStreamReader(is);
                FileWriter fw = new FileWriter(confFile);
                int b = isr.read();

                while (b != -1) {
                    fw.write(b);
                    b = isr.read();
                }

                fw.flush();
            } catch (Exception ex) {
                log.error("Error writing Config File from upload stream.", ex);
            }
        }
    }

    if (Configuration.configOK()) {
        log.info("Uploaded valid Config");
    }

    model.setUserName("admin");
    model.setCurrentPage("setup2.jsp");
}