Example usage for java.io Writer flush

List of usage examples for java.io Writer flush

Introduction

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

Prototype

public abstract void flush() throws IOException;

Source Link

Document

Flushes the stream.

Usage

From source file:com.norconex.importer.ImporterConfig.java

private void writeObject(Writer out, String tagName, Object object, boolean ignore) throws IOException {
    if (object == null) {
        if (ignore) {
            out.write("<" + tagName + " ignore=\"" + ignore + "\" />");
        }/*from w w w  .  j a va  2  s  .  c o m*/
        return;
    }
    StringWriter w = new StringWriter();
    if (object instanceof IXMLConfigurable) {
        ((IXMLConfigurable) object).saveToXML(w);
    } else {
        w.write("<" + tagName + " class=\"" + object.getClass().getCanonicalName() + "\" />");
    }
    String xml = w.toString();
    if (ignore) {
        xml = xml.replace("<" + tagName + " class=\"", "<" + tagName + " ignore=\"true\" class=\"");
    }
    out.write(xml);
    out.flush();
}

From source file:au.org.ala.bhl.command.ExtractPlacesCommand.java

public void execute(ItemsService service, IndexerOptions options) throws Exception {
    final DocumentCacheService cache = new DocumentCacheService(options.getDocCachePath());
    final File outputFile = new File(options.getOutputFile());

    if (outputFile.exists()) {
        outputFile.delete();//from   ww w.  jav a2 s . co m
    }

    final Writer writer = new FileWriter(outputFile);

    cache.forEachItemPage(new CachedItemPageHandler() {

        public void onPage(String internetArchiveId, String pageId, String text) {

            try {
                List<String> places = PlaceGrab.findPlaces(text);
                for (String place : places) {
                    String line = String.format("%s,%s,\"%s\"\n", internetArchiveId, pageId, place);
                    writer.write(line);
                    System.err.println(place);
                }
            } catch (IOException ioex) {
                throw new RuntimeException(ioex);
            }

        }

        public void startItem(String internetArchiveId) {
            log("Starting item %s", internetArchiveId);
        }

        public void endItem(String itemId) {
            try {
                writer.flush();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    });

}

From source file:au.org.ala.biocache.dao.TaxonDAOImpl.java

void outputLayer(String metadataUrlRoot, String rank, String taxon, Writer out) throws Exception {
    String normalised = taxon.replaceFirst("\\([A-Za-z]*\\) ", "").replace(" ", "_").replace("&", "&amp;"); //remove the subgenus, replace spaces with underscores
    String normalisedTitle = taxon.replaceFirst("\\([A-Za-z]*\\) ", "").replace("&", "&amp;"); //remove the subgenus, replace spaces with underscores

    out.write("<Layer queryable=\"1\"><Name>" + rank + ":" + normalised + "</Name><Title>" + rank + ":"
            + normalisedTitle + "</Title>" + "<MetadataURL type=\"TC211\">\n" + "<Format>text/html</Format>\n"
            + "<OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:type=\"simple\""
            + " xlink:href=\"" + metadataUrlRoot + "?q=" + rank + ":" + URLEncoder.encode(taxon, "UTF-8")
            + "\"/>\n" + "</MetadataURL>" + "</Layer>");
    out.flush();
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.processors.DataAccessMatrixQueriesMockImpl.java

public void addPathsToSelectedFiles(List<DataFile> selectedFiles) throws DAMQueriesException {
    //boolean ret = true;
    Reader in = null;/*from w w w  .j ava 2s. c  om*/
    Writer out = null;
    try {
        for (DataFile fileInfo : selectedFiles) {
            //noinspection IOResourceOpenedButNotSafelyClosed
            in = new BufferedReader(new FileReader(testDownloadFile));
            String fname = dataFilePath + fileInfo.getFileId() + ".idat";
            File f = new File(fname);
            if (f.exists()) {
                f.delete();
            }
            //noinspection IOResourceOpenedButNotSafelyClosed
            out = new BufferedWriter(new FileWriter(fname));
            int c;
            while ((c = in.read()) != -1) {
                out.write(c);
            }
            out.flush();
            out.close();
            in.close();
            System.out.println("wrote file " + fname);
            fileInfo.setPath(fname);
            fname = fname.replace('\\', '/');
            fname = fname.substring(fname.lastIndexOf('/') + 1);
            fileInfo.setFileName(fname);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        //all or nothing
        for (DataFile fileInfo : selectedFiles) {
            fileInfo.setPath(null);
        }
        //ret = false;
        throw new DAMQueriesException(ex);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
    //return ret;
}

From source file:com.coinblesk.client.backup.BackupDialogFragment.java

private void backup() {
    final File backupFile = newWalletBackupFile();
    final String password = txtPassword.getText().toString();
    Preconditions.checkState(password.equals(txtPasswordAgain.getText().toString()) && password.length() > 0);
    clearPasswordInput();/*  w w w . java 2  s  . c o  m*/

    Writer fileOut = null;
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final ZipOutputStream zos = new ZipOutputStream(baos);
        Log.i(TAG, "Backup file: " + backupFile);

        // assemble all content to backup
        addFilesToZip(zos);

        // encrypt zip bytes and write to file
        zos.close();
        byte[] plainBackup = baos.toByteArray();
        String encryptedBackup = EncryptionUtils.encrypt(plainBackup, password.toCharArray());
        fileOut = new OutputStreamWriter(new FileOutputStream(backupFile), Charsets.UTF_8);
        fileOut.write(encryptedBackup);
        fileOut.flush();
        Log.i(TAG, "Wallet backup finished. File = [" + backupFile + "], size = " + backupFile.length()
                + "bytes, exists = " + backupFile.exists());

        // ask user whether he wants backup file as mail attachment
        showBackupCompletedDialog(backupFile);

    } catch (Exception e) {
        Log.w(TAG, "Could not write to file", e);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.fragment_backup_failed_title)
                .setMessage(getString(R.string.fragment_backup_failed_message) + ": " + e.getMessage())
                .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                    }
                }).create().show();
    } finally {
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (IOException e) {
                Log.i(TAG, "Could not close output stream");
            }
        }
    }
}

From source file:com.amalto.core.storage.record.ViewSearchResultsWriter.java

@Override
public void write(DataRecord record, Writer writer) throws IOException {
    writer.write("<result xmlns:metadata=\"" + DataRecordReader.METADATA_NAMESPACE + "\"" //$NON-NLS-1$ //$NON-NLS-2$
            + " xmlns:xsi=\"" + XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$
    for (FieldMetadata fieldMetadata : record.getSetFields()) {
        Object value = record.get(fieldMetadata);
        String name = fieldMetadata.getName();
        if (value != null) {
            writer.append("\t<").append(name).append(">"); //$NON-NLS-1$ //$NON-NLS-2$
            processValue(writer, fieldMetadata, value);
            writer.append("</").append(name).append(">\n"); //$NON-NLS-1$ //$NON-NLS-2$
        } else {/*  w  w w .  j av  a 2 s . c  o m*/
            writer.append("\t<").append(name).append("/>\n"); //$NON-NLS-1$//$NON-NLS-2$
        }
    }
    writer.append("</result>"); //$NON-NLS-1$
    writer.flush();
}

From source file:com.npower.unicom.sync.FileSyncItemWriter.java

public void close() throws IOException {
    this.writer.flush();
    this.writer.close();

    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    Writer out = new FileWriter(this.file);
    out.write("0001");
    out.write('\t');
    out.write("00000");
    out.write('\t');
    out.write(format.format(new Date()));
    out.write('\t');
    out.write("ZB");
    out.write('\t');

    String from = (fromDate != null) ? format.format(fromDate) : "19700101000000";
    String to = (toDate != null) ? format.format(toDate) : "19700101000000";

    out.write(from);//from ww  w.j  ava 2s . co m
    out.write('\t');
    out.write(to);
    out.write('\t');
    out.write(Integer.toString(this.totalRecords));
    out.write('\t');
    out.write('\n');
    // 
    FileReader in = new FileReader(this.bodyFile);
    char[] buf = new char[512];
    int len = in.read(buf);
    while (len > 0) {
        out.write(buf, 0, len);
        out.flush();
        len = in.read(buf);
    }
    in.close();
    out.close();
}

From source file:EditorPaneExample7.java

public EditorPaneExample7() {
    super("JEditorPane Example 7");

    pane = new JEditorPane();
    pane.setEditable(false); // Start read-only
    getContentPane().add(new JScrollPane(pane), "Center");

    // Build the panel of controls
    JPanel panel = new JPanel();

    panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.gridwidth = 1;/*from ww  w  .j a v  a2  s.  co m*/
    c.gridheight = 1;
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.0;
    c.weighty = 0.0;

    JLabel urlLabel = new JLabel("File name: ", JLabel.RIGHT);
    panel.add(urlLabel, c);
    JLabel loadingLabel = new JLabel("State: ", JLabel.RIGHT);
    c.gridy = 1;
    panel.add(loadingLabel, c);
    JLabel typeLabel = new JLabel("Type: ", JLabel.RIGHT);
    c.gridy = 2;
    panel.add(typeLabel, c);

    c.gridx = 1;
    c.gridy = 0;
    c.gridwidth = 1;
    c.weightx = 1.0;
    c.fill = GridBagConstraints.HORIZONTAL;

    textField = new JTextField(32);
    panel.add(textField, c);
    loadingState = new JLabel(spaces, JLabel.LEFT);
    loadingState.setForeground(Color.black);
    c.gridy = 1;
    c.gridwidth = 2;
    panel.add(loadingState, c);
    loadedType = new JLabel(spaces, JLabel.LEFT);
    loadedType.setForeground(Color.black);
    c.gridy = 2;
    panel.add(loadedType, c);

    getContentPane().add(panel, "South");

    panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

    saveButton = new JButton("Save");
    plain = new JCheckBox("Plain Text");
    html = new JCheckBox("HTML");
    rtf = new JCheckBox("RTF");
    panel.add(plain);
    panel.add(html);
    panel.add(rtf);

    ButtonGroup group = new ButtonGroup();
    group.add(plain);
    group.add(html);
    group.add(rtf);
    plain.setSelected(true);

    panel.add(Box.createVerticalStrut(10));
    panel.add(saveButton);
    panel.add(Box.createVerticalGlue());
    panel.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));

    getContentPane().add(panel, "East");

    // Change page based on text field
    textField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            String fileName = textField.getText().trim();
            file = new File(fileName);
            absolutePath = file.getAbsolutePath();
            String url = "file:///" + absolutePath;

            try {
                // Check if the new page and the old
                // page are the same.
                URL newURL = new URL(url);
                URL loadedURL = pane.getPage();
                if (loadedURL != null && loadedURL.sameFile(newURL)) {
                    return;
                }

                // Try to display the page
                textField.setEnabled(false); // Disable input
                textField.paintImmediately(0, 0, textField.getSize().width, textField.getSize().height);

                saveButton.setEnabled(false);
                saveButton.paintImmediately(0, 0, saveButton.getSize().width, saveButton.getSize().height);
                setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                // Busy cursor
                loadingState.setText("Loading...");
                loadingState.paintImmediately(0, 0, loadingState.getSize().width,
                        loadingState.getSize().height);
                loadedType.setText("");
                loadedType.paintImmediately(0, 0, loadedType.getSize().width, loadedType.getSize().height);
                pane.setEditable(false);
                pane.setPage(url);

                loadedType.setText(pane.getContentType());
            } catch (Exception e) {
                JOptionPane.showMessageDialog(pane, new String[] { "Unable to open file", url },
                        "File Open Error", JOptionPane.ERROR_MESSAGE);
                loadingState.setText("Failed");
                textField.setEnabled(true);
                setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    // Listen for page load to complete
    pane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("page")) {
                loadingState.setText("Page loaded.");

                textField.setEnabled(true); // Allow entry of new file name
                textField.requestFocus();
                setCursor(Cursor.getDefaultCursor());

                // Allow editing and saving if appropriate
                pane.setEditable(file.canWrite());
                saveButton.setEnabled(file.canWrite());
            }
        }
    });

    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            Writer w = null;
            OutputStream os = System.out;
            String contentType;
            if (plain.isSelected()) {
                contentType = "text/plain";
                w = new OutputStreamWriter(os);
            } else if (html.isSelected()) {
                contentType = "text/html";
                w = new OutputStreamWriter(os);
            } else {
                contentType = "text/rtf";
            }

            EditorKit kit = pane.getEditorKitForContentType(contentType);
            try {
                if (w != null) {
                    kit.write(w, pane.getDocument(), 0, pane.getDocument().getLength());
                    w.flush();
                } else {
                    kit.write(os, pane.getDocument(), 0, pane.getDocument().getLength());
                    os.flush();
                }
            } catch (Exception e) {
                System.out.println("Write failed");
            }
        }
    });
}

From source file:org.fao.fenix.wds.web.rest.faostat.FAOSTATExporter.java

@POST
@Path("/excel")
public Response createExcel(@FormParam("data") final String data) {

    // Initiate the stream
    StreamingOutput stream = new StreamingOutput() {

        @Override//from ww w .  j ava  2  s . c  om
        public void write(OutputStream os) throws IOException, WebApplicationException {

            // initiate variables
            Gson g = new Gson();
            String[][] array = g.fromJson(data, String[][].class);
            Writer writer = new BufferedWriter(new OutputStreamWriter(os));

            // Create HTML to be converted in Excel
            StringBuilder sb = new StringBuilder();
            sb.append("<table>");
            for (int i = 0; i < array.length; i++) {
                sb.append("<tr>");
                String[] row = array[i];
                for (String s : row)
                    sb.append("<td>").append(s).append("</td>");
                sb.append("</tr>");
            }
            sb.append("</table>");

            // Write to the stream
            writer.write(sb.toString());
            writer.flush();

        }

    };

    // Wrap result
    ResponseBuilder builder = Response.ok(stream);
    //        builder.header("Access-Control-Allow-Origin", "*");
    //        builder.header("Access-Control-Max-Age", "3600");
    //        builder.header("Access-Control-Allow-Methods", "GET");
    //        builder.header("Access-Control-Allow-Headers", "X-Requested-With, Host, User-Agent, Accept, Accept-Language, Accept-Encoding, Accept-Charset, Keep-Alive, Connection, Referer,Origin");
    builder.header("Content-Disposition", "attachment; filename=" + UUID.randomUUID().toString() + ".xls");

    // Stream Excel
    return builder.build();

}

From source file:io.github.arven.flare.boot.TomcatContainer.java

private void copyTemplateTo(final File targetDir, final String filename) throws Exception {
    // don't break apps using Velocity facade
    final VelocityEngine engine = new VelocityEngine();
    engine.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
    engine.setProperty(Velocity.RESOURCE_LOADER, "class");
    engine.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
    engine.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
    engine.init();/*from  w  ww  .ja va2s . c  o m*/
    final Template template = engine.getTemplate("/org/apache/tomee/configs/" + filename);
    final VelocityContext context = new VelocityContext();
    context.put("tomcatHttpPort", Integer.toString(configuration.getHttpPort()));
    context.put("tomcatShutdownPort", Integer.toString(configuration.getStopPort()));
    final Writer writer = new FileWriter(new File(targetDir, filename));
    template.merge(context, writer);
    writer.flush();
    writer.close();
}