Example usage for java.io Writer close

List of usage examples for java.io Writer close

Introduction

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

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream, flushing it first.

Usage

From source file:com.machinelinking.converter.ScriptableConverterTest.java

@Test
public void testConvert() throws IOException, ConverterException, ScriptableFactoryException {
    final String script = IOUtils
            .toString(this.getClass().getResourceAsStream("scriptable-converter-test1.py"));
    final ScriptableConverter converter = ScriptableConverterFactory.getInstance().createConverter(script);
    final ByteArrayOutputStream serializerBAOS = new ByteArrayOutputStream();
    final JSONSerializer serializer = new JSONSerializer(serializerBAOS);
    final ByteArrayOutputStream writerBAOS = new ByteArrayOutputStream();
    final Writer writer = new BufferedWriter(new OutputStreamWriter(writerBAOS));
    converter.convertData(JSONUtils/* www.jav  a2s .  c om*/
            .parseJSONAsMap("{\"@type\":\"reference\",\"label\":\"List of Nobel laureates in Physics\","
                    + "\"content\":{\"@an0\":\"1921\"}}"),
            serializer, writer);
    serializer.close();
    writer.close();
    Assert.assertEquals(serializerBAOS.toString(), "{\"link\":\"List of Nobel laureates in Physics 1921\"}");
    Assert.assertEquals(writerBAOS.toString(), "<a href=\"List of Nobel laureates in Physics\">1921</a>");
}

From source file:me.wxwsk8er.Knapsack.Configuration.JSONConfiguration.java

@Override
public void save() {
    Writer writer = null;

    try {//from   w ww  .  j av a  2  s.  com
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.filePath), "utf-8"));
        writer.write(jObject.toJSONString());
        writer.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:EditorPaneExample6.java

public EditorPaneExample6() {
    super("JEditorPane Example 6");

    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;//  www.  j a va 2s.c  o  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);

    // Add a "Save" button
    saveButton = new JButton("Save");
    saveButton.setEnabled(false);
    c.gridwidth = 1;
    c.gridx = 2;
    c.gridy = 0;
    c.weightx = 0.0;
    panel.add(saveButton, c);

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

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

    // Save button
    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            try {
                String type = pane.getContentType();
                OutputStream os = new BufferedOutputStream(new FileOutputStream(file + ".save"));
                pane.setEditable(false);
                textField.setEnabled(false);
                saveButton.setEnabled(false);
                setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                Document doc = pane.getDocument();
                int length = doc.getLength();
                if (type.endsWith("/rtf")) {
                    // Saving RTF - use the OutputStream
                    try {
                        pane.getEditorKit().write(os, doc, 0, length);
                        os.close();
                    } catch (BadLocationException ex) {
                    }
                } else {
                    // Not RTF - use a Writer.
                    Writer w = new OutputStreamWriter(os);
                    pane.write(w);
                    w.close();
                }
            } catch (IOException e) {
                JOptionPane.showMessageDialog(pane,
                        new String[] { "Unable to save file", file.getAbsolutePath(), }, "File Save Error",
                        JOptionPane.ERROR_MESSAGE);

            }
            pane.setEditable(file.canWrite());
            textField.setEnabled(true);
            saveButton.setEnabled(file.canWrite());
            setCursor(Cursor.getDefaultCursor());
        }
    });
}

From source file:com.streamsets.pipeline.stage.origin.spooldir.TestLogSpoolDirSourceApacheCustomLogFormat.java

private File createLogFile() throws Exception {
    File f = new File(createTestDir(), "test.log");
    Writer writer = new FileWriter(f);
    IOUtils.write(LINE1 + "\n", writer);
    IOUtils.write(LINE2, writer);//from  w  ww  . j av a  2 s . c  o  m
    writer.close();
    return f;
}

From source file:com.netxforge.oss2.config.PollerConfigFactory.java

/** {@inheritDoc} */
protected void saveXml(final String xml) throws IOException {
    if (xml != null) {
        getWriteLock().lock();/*  w  w  w.j  a v a  2  s.c  o m*/
        try {
            final long timestamp = System.currentTimeMillis();
            final File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.POLLER_CONFIG_FILE_NAME);
            LogUtils.debugf(this, "saveXml: saving config file at %d: %s", timestamp, cfgFile.getPath());
            final Writer fileWriter = new OutputStreamWriter(new FileOutputStream(cfgFile), "UTF-8");
            fileWriter.write(xml);
            fileWriter.flush();
            fileWriter.close();
            LogUtils.debugf(this, "saveXml: finished saving config file: %s", cfgFile.getPath());
        } finally {
            getWriteLock().unlock();
        }
    }
}

From source file:cc.kune.core.server.manager.file.FileUploadManagerAbstract.java

/**
 * Do response.//from  w  w  w  .  j  a  v a2s. com
 * 
 * @param response
 *          the response
 * @param additionalResponse
 *          the additional response
 * @param responseCode
 *          the response code
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
protected void doResponse(final HttpServletResponse response, final String additionalResponse,
        final int responseCode) throws IOException {
    final Writer w = new OutputStreamWriter(response.getOutputStream());
    if (additionalResponse != null) {
        w.write(additionalResponse);
    }
    w.close();
    response.setStatus(responseCode);
}

From source file:net.itransformers.idiscover.v2.core.node_discoverers.bgpdiscoverer.BGPMapNetworkDiscoverer.java

protected void startDiscovery(Set<ConnectionDetails> connectionDetailsList) {

    NetworkDiscoveryResult result = new NetworkDiscoveryResult(null);

    for (ConnectionDetails connectionDetails : connectionDetailsList) {

        if (!"javaMRT".equals(connectionDetails.getConnectionType())) {
            logger.debug("Connection details are not for javaMRTfile");

            return;
        }/*ww w  .java2s.  c  om*/

        String pathToFile = connectionDetails.getParam("pathToFile");
        String version = connectionDetails.getParam("version");

        String[] args = new String[4];
        args[0] = "-f";

        args[1] = pathToFile;

        args[2] = "-o";
        String outputFile = ProjectConstants.networkGraphmlFileName;
        args[3] = outputFile;

        Map<String, String> params = CmdLineParser.parseCmdLine(args);

        StringWriter writer = new StringWriter();

        String file = null;
        OutputStream logOutputStream = new NullOutputStream();

        if (params.containsKey("-f")) {
            file = params.get("-f");
        } else {
            logger.info("no file passed");
            System.exit(1);
        }

        ASContainer ases = new ASContainer();
        System.out.println("Start reading MRT file");
        File tmpEdgeFile = null;
        try {
            tmpEdgeFile = File.createTempFile("test" + "_", ".txt");
            System.out.println("Creating edge tmp file: " + tmpEdgeFile.getAbsolutePath());
            Writer edgeWriter = new PrintWriter(tmpEdgeFile);

            Route2GraphmlDumper.dumpToXmlString(new String[] { file }, new PrintWriter(logOutputStream),
                    edgeWriter, ases);
            edgeWriter.close();
            Route2GraphmlDumper.dumpGraphml(ases, writer, tmpEdgeFile);

        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.

        } finally {
            tmpEdgeFile.delete();

        }

        NodeDiscoveryResult result1 = new NodeDiscoveryResult(null, null, null);

        result1.setDiscoveredData("version", version);
        result1.setDiscoveredData("graphml", writer.toString().getBytes());
        result1.setDiscoveredData("discoverer", "javaMRT");

        result.addDiscoveredData(file, result1);

    }
    fireNetworkDiscoveredEvent(result);

}

From source file:ca.rmen.android.networkmonitor.app.email.Emailer.java

/**
 * Sends an e-mail in UTF-8 encoding./* w  w w .j  av  a2s. c  o m*/
 *
 * @param protocol    this has been tested with "TLS", "SSL", and null.
 * @param attachments optional attachments to include in the mail.
 * @param debug       if true, details about the smtp commands will be logged to stdout.
 */
static void sendEmail(String protocol, String server, int port, String user, String password, String from,
        String[] recipients, String subject, String body, Set<File> attachments, boolean debug)
        throws Exception {

    // Set up the mail connectivity
    final AuthenticatingSMTPClient client;
    if (protocol == null)
        client = new AuthenticatingSMTPClient();
    else
        client = new AuthenticatingSMTPClient(protocol);

    if (debug)
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    client.setDefaultTimeout(SMTP_TIMEOUT_MS);
    client.setCharset(Charset.forName(ENCODING));
    client.connect(server, port);
    checkReply(client);
    client.helo("[" + client.getLocalAddress().getHostAddress() + "]");
    checkReply(client);
    if ("TLS".equals(protocol)) {
        if (!client.execTLS()) {
            checkReply(client);
            throw new RuntimeException("Could not start tls");
        }
    }
    client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, user, password);
    checkReply(client);

    // Set up the mail participants
    client.setSender(from);
    checkReply(client);
    for (String recipient : recipients) {
        client.addRecipient(recipient);
        checkReply(client);
    }

    // Set up the mail content
    Writer writer = client.sendMessageData();
    SimpleSMTPHeader header = new SimpleSMTPHeader(from, recipients[0], subject);
    for (int i = 1; i < recipients.length; i++)
        header.addCC(recipients[i]);

    // Just plain text mail: no attachments
    if (attachments == null || attachments.isEmpty()) {
        header.addHeaderField("Content-Type", "text/plain; charset=" + ENCODING);
        writer.write(header.toString());
        writer.write(body);
    }
    // Mail with attachments
    else {
        String boundary = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 28);
        header.addHeaderField("Content-Type", "multipart/mixed; boundary=" + boundary);
        writer.write(header.toString());

        // Write the main text message
        writer.write("--" + boundary + "\n");
        writer.write("Content-Type: text/plain; charset=" + ENCODING + "\n\n");
        writer.write(body);
        writer.write("\n");

        // Write the attachments
        appendAttachments(writer, boundary, attachments);
        writer.write("--" + boundary + "--\n\n");
    }

    writer.close();
    if (!client.completePendingCommand()) {
        throw new RuntimeException("Could not send mail");
    }
    client.logout();
    client.disconnect();
}

From source file:com.c4om.autoconf.ulysses.configanalyzer.guilauncher.ChromeAppEditorGUILauncher.java

/**
 * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.GUILauncher#launchGUI(com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.datastructures.ConfigurationAnalysisContext, com.c4om.autoconf.ulysses.interfaces.Target)
 *///  w  w w  . ja  va  2 s .c om
@SuppressWarnings("resource")
@Override
public void launchGUI(ConfigurationAnalysisContext context, Target target) throws GUILaunchException {
    try {
        List<File> temporaryFolders = this.getTemporaryStoredChangesetsAndConfigs(context, target);

        for (File temporaryFolder : temporaryFolders) {

            //The temporary folder where one subfolder per analyzer execution will be stored (and removed).
            File temporaryFolderRoot = temporaryFolder.getParentFile().getParentFile();

            System.out.println("Writing launch properties.");

            //Now, we build the properties file
            Properties launchProperties = new Properties();
            String relativeTemporaryFolder = temporaryFolder.getAbsolutePath()
                    .replaceAll("^" + Pattern.quote(temporaryFolderRoot.getAbsolutePath()), "")
                    .replaceAll("^" + Pattern.quote(File.separator), "")
                    .replaceAll(Pattern.quote(File.separator) + "$", "")
                    .replaceAll(Pattern.quote(File.separator) + "+", "/");
            //            launchProperties.put(KEY_LOAD_RECOMMENDATIONS_FILE, relativeTemporaryFolder+CHANGESET_TO_APPLY);
            launchProperties.put(KEY_CATALOG, relativeTemporaryFolder + CATALOG_FILE_PATH);
            Writer writer = new OutputStreamWriter(
                    new FileOutputStream(new File(temporaryFolderRoot, LAUNCH_PROPERTIES_FILE_NAME)),
                    Charsets.UTF_8);
            launchProperties.store(writer, "");
            writer.close();
            System.out.println("Launch properties written!!!!");

            System.out.println("Launching XML editor Chrome app");

            Properties configurationAnalyzerProperties = context.getConfigurationAnalyzerSettings();
            String chromeLocation = configurationAnalyzerProperties.getProperty(PROPERTIES_KEY_CHROME_LOCATION);
            String editorChromeAppLocation = configurationAnalyzerProperties
                    .getProperty(PROPERTIES_KEY_EDITOR_CHROME_APP_LOCATION);

            ProcessBuilder chromeEditorPB = new ProcessBuilder(
                    ImmutableList.of(chromeLocation, "--load-and-launch-app=" + editorChromeAppLocation));
            chromeEditorPB.directory(new File(editorChromeAppLocation));
            chromeEditorPB.start();
            System.out.println("Editor started!!!");
            System.out.println("Now, make all your changes and press ENTER when finished...");
            new Scanner(System.in).nextLine();
            FileUtils.forceDeleteOnExit(temporaryFolder.getParentFile());

        }
    } catch (IOException e) {
        throw new GUILaunchException(e);
    }
}

From source file:gdv.xport.util.NullFormatterTest.java

/**
 * Test-Methode fuer {@link NullFormatter#write(Datenpaket)}.
 * Hier testen wir, ob der Formatter tatsaechlich keine Formattierung
 * vornimmt und als Result die gleiche Datei wie die Eingabe-Datei
 * rausschreibt./* w  ww .ja  va2  s.  c o  m*/
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
@IntegrationTest
@Test
public void testWriteDatenpaketToFile() throws IOException {
    File output = File.createTempFile("output", ".txt");
    Writer writer = new OutputStreamWriter(new FileOutputStream(output), "ISO-8859-1");
    NullFormatter formatter = new NullFormatter(writer);
    Datenpaket datenpaket = new Datenpaket();
    try {
        datenpaket.importFrom(MUSTERDATEI, "ISO-8859-1");
        formatter.write(datenpaket);
        writer.close();
        FileTester.assertContentEquals(MUSTERDATEI, output, "ISO-8859-1");
    } finally {
        log.info(output + " was " + (output.delete() ? "successful" : "not") + " deleted");
    }
}