Example usage for java.io FileWriter append

List of usage examples for java.io FileWriter append

Introduction

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

Prototype

@Override
    public Writer append(CharSequence csq) throws IOException 

Source Link

Usage

From source file:net.ceos.project.poi.annotated.core.CGen.java

/**
 * Add the content of one line stored at the Map into the file.
 * //from  w ww . jav  a2s .  co m
 * @param fW
 *            the file to write
 * @param values
 *            the Map with the data to write at the file
 * @throws IOException
 */
private void addLine(final FileWriter fW, final Map<Integer, String> values, final String separator)
        throws IOException {
    /* append all values at the Map to the file */
    fW.append(values.values().stream().collect(Collectors.joining(separator)));
    /* add end of line */
    fW.append(Constants.END_OF_LINE);
}

From source file:dk.netarkivet.archive.checksum.FileChecksumArchive.java

/**
 * Method for retrieving the names of all the files within the archive as a temporary file.
 *
 * @return A temporary file containing the list of all the filenames. This file has one filename per line.
 * @throws IOFailure If problems occurs during the creation of the file.
 *///  w  w w.  j  a  va  2  s . com
@Override
public File getAllFilenames() throws IOFailure {
    synchronizeMemoryWithFile();

    try {
        File tempFile = File.createTempFile("tmp", "tmp", FileUtils.getTempDir());
        FileWriter fw = new FileWriter(tempFile);

        try {
            // put the content into the file.
            for (String filename : checksumArchive.keySet()) {
                fw.append(filename);
                fw.append("\n");
            }

        } finally {
            // flush and close the file, before returning it.
            fw.flush();
            fw.close();
        }
        return tempFile;
    } catch (IOException e) {
        String msg = "Cannot create the output file containing the filenames of all the entries of this archive.";
        log.warn(msg);
        throw new IOFailure(msg);
    }
}

From source file:org.directwebremoting.drapgen.generate.gi.GiType.java

/**
 * @param directory Where to write the xml
 * @throws java.io.IOException If writing fails
 *//* w  w  w .  j  a  va 2  s  . co m*/
public void writeDOM(String directory) throws IOException {
    FileWriter out = null;

    try {
        Transformer transformer = factory.newTransformer();
        Source source = new DOMSource(document);

        StringWriter xml = new StringWriter();
        StreamResult result = new StreamResult(xml);

        transformer.transform(source, result);

        xml.flush();

        String domName = xmlClassName.replaceAll("/", ".");
        File domFile = new File(directory + "org.directwebremoting.proxy." + domName);
        out = new FileWriter(domFile);
        out.append(xml.toString());
    } catch (TransformerException ex) {
        SourceLocator locator = ex.getLocator();
        log.fatal("Failed to transform", ex);
        log.warn("Line: " + locator.getLineNumber() + ", Column: " + locator.getColumnNumber());
        log.warn("PublicId: " + locator.getPublicId());
        log.warn("SystemId: " + locator.getSystemId());
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:dk.netarkivet.archive.checksum.DatabaseChecksumArchive.java

/**
 * Write the contents of the database to the given file.
 *
 * @param outputFile The outputfile whereto the data is written.
 * @param writeOnlyFilenames If true, we only write the filenames to the files, not the checksums
 * @throws IOException If unable to write to file for some reason
 *///from   w  ww .j a  v  a  2s  .  com
private void dumpDatabaseToFile(File tempFile, boolean writeOnlyFilenames) throws IOException {
    Cursor cursor = null;
    File resultFile = tempFile;

    FileWriter fw = new FileWriter(resultFile);
    try {
        cursor = checksumDB.openCursor(null, null);

        DatabaseEntry foundKey = new DatabaseEntry();
        DatabaseEntry foundData = new DatabaseEntry();

        while (cursor.getNext(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
            String keyString = new String(foundKey.getData());
            String dataString = new String(foundData.getData());
            if (writeOnlyFilenames) {
                fw.append(keyString);
            } else {
                fw.append(keyString);
                fw.append(ChecksumJob.STRING_FILENAME_SEPARATOR);
                fw.append(dataString);
            }
            fw.append('\n'); // end with newline
        }
        fw.flush();
    } catch (DatabaseException de) {
        throw new IOFailure("Error accessing database." + de);
    } finally {
        if (fw != null) {
            IOUtils.closeQuietly(fw);
        }
        if (cursor != null) {
            try {
                cursor.close();
            } catch (DatabaseException e) {
                log.warn("Database error occurred when closing the cursor: ", e);
            }
        }
    }
}

From source file:org.codehaus.mojo.exec.ExecMojo.java

private void createArgFile(String filePath, List<String> lines) throws IOException {
    final String EOL = System.getProperty("line.separator", "\\n");

    FileWriter writer = null;
    try {//  w  w w.  j  av a  2  s.c o  m
        writer = new FileWriter(filePath);
        for (String line : lines) {
            writer.append(line).append(EOL);
        }

    } finally {
        IOUtil.close(writer);
    }
}

From source file:org.talend.migrationtool.MigrationToolService.java

private void appendToLogFile(Project sourceProject, String logTxt) {
    IProject project = ProjectManager.getInstance().getResourceProject(sourceProject.getEmfProject());
    File fullLogFile = new File(project.getFile(FULL_LOG_FILE).getLocation().toPortableString());

    FileWriter writer = null;
    try {//from  w  ww. j a v  a  2s  .  co  m
        writer = new FileWriter(fullLogFile, true);
        writer.append(logTxt);
    } catch (IOException e) {
        // nothing
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                // do nothing
            }
        }
    }

}

From source file:ca.uhn.hl7v2.testpanel.controller.Prefs.java

private void sync() {

    Runnable r = new Runnable() {
        @Override//from   w  w w  . j ava 2s . co  m
        public void run() {
            StringWriter writer = new StringWriter();
            try {
                ourJaxbContext.createMarshaller().marshal(Prefs.this, writer);
            } catch (JAXBException e) {
                ourLog.error("Failed to marshall prefs! This shouldn't happen", e);
            }

            final String prefs = writer.toString();
            if (StringUtils.equals(myLastPrefsFileSaveValue, prefs)) {
                return;
            }

            ourLog.info("Syncing user preferences to disk");

            try {
                FileWriter w = new FileWriter(getPrefsFile(), false);
                w.append(prefs);
                w.close();

                ourLog.info("Done synchronizing user prefs ({} chars)", prefs.length());
                myLastPrefsFileSaveValue = prefs;

                try {
                    ourPrefs.clear();
                } catch (BackingStoreException e) {
                    // we can ignore this
                }

            } catch (IOException e) {
                ourLog.error("Failed to write prefs file to disk", e);
            }

        }
    };

    if (myController != null) {
        myController.invokeInBackground(r);
    }

}

From source file:org.n52.ifgicopter.spf.gui.SPFMainFrame.java

/**
 * This adds an {@link IInputPlugin} to the gui.
 * //ww w.j a  v  a  2 s .  c o m
 * @param ip
 *        the input plugin
 */
public void addInputPlugin(final IInputPlugin ip) {
    this.corePanel.addInputPlugin(ip);

    ModuleGUI ui = ip.getUserInterface();

    /*
     * if the plugin does not have a gui, create a default one.
     */
    if (ui == null) {
        ui = createDefaultInputUI(ip);
    } else {
        /*
         * add the tab
         */
        this.addTab(ui.getGui(), ip.getName(), RED_IMAGE);
    }

    this.inputPluginPanels.put(ip, ui);

    /*
     * menu if it has one
     */
    JMenu men = ui.getMenu();
    if (men == null) {
        men = new JMenu();
    }
    men.setText(ip.getName());

    /*
     * add an entry for the metadata and xml export
     */
    JMenuItem metas = new JMenuItem("Edit Metadata");
    metas.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Plugin plug = SPFRegistry.getInstance().getPluginForName(ip.getName());
            InputMetadataDialog dial = new InputMetadataDialog(plug.getMetadata(), SPFMainFrame.this);
            dial.setVisible(true);
        }
    });
    men.add(metas);

    JMenuItem export = new JMenuItem("Export XML description");
    export.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Plugin plug = SPFRegistry.getInstance().getPluginForName(ip.getName());
            String string = PluginXMLTools.toXML(plug);

            String tmp = "plugin-description-" + plug.getName() + ".xml";
            tmp = tmp.replace(":", "_");
            File file = new File(tmp);

            try {
                if (!file.exists()) {
                    boolean b = file.createNewFile();
                    if (!b)
                        SPFMainFrame.this.log.warn("File already exists!");
                }
                FileWriter fw = new FileWriter(file);

                fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                fw.append(System.getProperty("line.separator"));
                fw.write(string);
                fw.flush();
                fw.close();
                SPFMainFrame.this.statusLabel.setText("XML written to " + file.getAbsolutePath());
            } catch (IOException e1) {
                SPFMainFrame.this.log.warn(e1.getMessage(), e1);
                SPFMainFrame.this.statusLabel
                        .setText("Failed writing XML description. (" + e1.getMessage() + ")");
            }

        }
    });
    men.add(export);

    this.inputPluginMenu.add(men);
}

From source file:dk.netarkivet.archive.checksum.FileChecksumArchive.java

/**
 * Recreates the archive file from the memory. Makes a new file which contains the entire archive, and then move the
 * new archive file on top of the old one. This is used when to recreate the archive file, when an record has been
 * removed./*from   ww  w  .  j a  v a  2  s. c  o m*/
 *
 * @throws IOFailure If a problem occur when writing the new file.
 */
private void recreateArchiveFile() throws IOFailure {
    try {
        // Handle the case, when there is not enough space left for
        // recreating the
        if (!hasEnoughSpaceForRecreate()) {
            log.error("Not enough space left to recreate the checksum file.");
            throw new IOFailure("Not enough space left to recreate the checksum file.");
        }

        // This should be synchronized, so no new entries can be made
        // while recreating the archive file.
        synchronized (checksumFile) {
            // initialize and create the file.
            File recreateFile = new File(checksumFile.getParentFile(), makeRecreateFileName());
            if (!recreateFile.createNewFile()) {
                log.warn("Cannot create new file. The recreate checksum file did already exist.");
            }

            // put the archive into the file.
            FileWriter fw = new FileWriter(recreateFile);
            try {
                for (Map.Entry<String, String> entry : checksumArchive.entrySet()) {
                    String record = entry.getKey() + CHECKSUM_SEPARATOR + entry.getValue();
                    fw.append(record + "\n");
                }
            } finally {
                fw.flush();
                fw.close();
            }

            // Move the file.
            FileUtils.moveFile(recreateFile, checksumFile);
        }
    } catch (IOException e) {
        String errMsg = "The checksum file has not been recreated as attempted. "
                + "The archive in memory and the one on file are no longer identical.";
        log.error(errMsg, e);
        throw new IOFailure(errMsg, e);
    }
}

From source file:org.eumetsat.usd.gcp.server.data.NetCDFCalibrationDataManager.java

/**
 * {@inheritDoc}/*from ww w.j  a  v a  2s. c o m*/
 */
@Override
public final void exportToCSVForUser(final String userID) throws FileException, FormulaException {
    final CalibrationData data = dataForUser(userID);

    final String userCsvFilePath = csvFilePath + "-" + userID + ".csv";

    // Deletes the file if already exists.
    File csvFile = new File(userCsvFilePath);

    if (csvFile.exists()) {
        csvFile.delete();
    }

    // Create FileWriter
    FileWriter writer = null;

    try {
        writer = new FileWriter(userCsvFilePath);

    } catch (IOException ioe) {
        throw new FileException("trying to open '" + userCsvFilePath + "'", ioe);
    }

    // Write to file.
    try {
        // Print first line with all sources names.
        writer.append("Date");

        for (String sourceName : dataForUser(userID).addedSources().keySet()) {
            writer.append("," + sourceName + ",1-sigma +/-");
        }

        writer.append("\n");

        // Sweep map in chronological order (since it is a TreeMap, i.e. sorted map)
        Set<Date> dates = dataForUser(userID).dates();
        Iterator<Date> itDates = dates.iterator();

        while (itDates.hasNext()) {
            Date date = itDates.next();

            // Write date (local [NOT UTC], because it is what dygraphs expects on the client
            // side).
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String dateStr = df.format(date);

            writer.append(dateStr);

            // Write records.
            CalibrationPacket dataPacket = data.getCalibrationPacket(date);

            // For each added source...
            for (Map.Entry<String, String> source : dataForUser(userID).addedSources().entrySet()) {
                // Get cal record.
                CalibrationRecord calRecord = dataPacket.getRecord(source.getKey());

                if (calRecord != null) {
                    // Write to file.
                    writer.append("," + calRecord.getTbBias() + "," + calRecord.getTbUncertainty() + ","
                            + calRecord.getTbUncertainty() + ",0.000000000001");

                } else {
                    // Write to file.
                    writer.append(",,,,");
                }
            }

            // Write to file.
            writer.append("\n");
        }

    } catch (IOException ioe) {
        throw new FileException("trying to append to '" + userCsvFilePath + "'", ioe);

    } finally {
        // Close writer.
        IOUtils.closeQuietly(writer);
    }

    LOGGER.info("'" + userCsvFilePath + "' successfully created.");
}