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:sandeep.kb.android.remote.android.AndroidWebDriver.java

void writeTo(String name, String toWrite) {
    try {// www.j ava2 s .  c o m
        File f = new File(".", name);
        FileWriter w = new FileWriter(f);
        w.append(toWrite);
        w.flush();
        w.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.sqoop.manager.sqlserver.SQLServerDatatypeImportSequenceFileManualTest.java

public void tearDown() {
    try {/*  ww w.  ja v a 2 s  .c o m*/
        super.tearDown();
    } catch (Exception e) {
        try {
            FileWriter fr = new FileWriter(getResportFileName(), true);
            String res = removeNewLines(e.getMessage());
            fr.append("Error\t" + res + "\n");
            fr.close();
        } catch (Exception e2) {
            LOG.error(StringUtils.stringifyException(e2));
            fail(e2.toString());
        }
    } catch (Error e) {
        try {
            FileWriter fr = new FileWriter(getResportFileName(), true);
            String res = removeNewLines(e.getMessage());
            fr.append("Error\t" + res + "\n");
            fr.close();
            fail(res);
        } catch (Exception e2) {
            LOG.error(StringUtils.stringifyException(e2));
            fail(e2.toString());
        }
    }
}

From source file:org.apache.sqoop.manager.sqlserver.SQLServerDatatypeImportSequenceFileManualTest.java

public void setUp() {
    try {/*from   w w w.j a v  a  2s  . c o  m*/
        super.setUp();
    } catch (Exception e) {
        try {
            FileWriter fr = new FileWriter(getResportFileName(), true);
            String res = removeNewLines(e.getMessage());
            fr.append("Error\t" + res + "\n");
            fr.close();
        } catch (Exception e2) {
            LOG.error(StringUtils.stringifyException(e2));
            fail(e2.toString());
        }
    } catch (Error e) {
        try {
            FileWriter fr = new FileWriter(getResportFileName(), true);

            String res = removeNewLines(e.getMessage());

            fr.append("Error\t" + res + "\n");
            fr.close();
            fail(res);
        } catch (Exception e2) {
            LOG.error(StringUtils.stringifyException(e2));
            fail(e2.toString());
        }
    }
}

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

/**
 * @param directory Base directory in which to write the Java files
 * @throws java.io.IOException If writing fails
 *//*from w  w w.  ja v  a 2  s.c  o m*/
public void writeCode(String directory) throws IOException {
    String javaClassName = xmlClassName.replaceFirst("\\.xml$", ".java");
    File javaFile = new File(directory + javaClassName);
    File javaParentDir = javaFile.getParentFile();

    if (!javaParentDir.isDirectory()) {
        if (!javaParentDir.mkdirs()) {
            throw new IOException("Failed to create directory: " + javaParentDir.getName());
        }
    }

    FileWriter out = null;

    try {
        StringBuffer outerCode = output.getBuffer();
        if (outerCode.toString().trim().length() != 0) {
            int closeCurly = outerCode.lastIndexOf("}");
            if (closeCurly != -1) {
                outerCode.delete(closeCurly, outerCode.length() - 1);
            }

            out = new FileWriter(javaFile);
            out.append(outerCode);

            for (GiType innerSource : innerSources) {
                String innerCode = innerSource.output.toString();
                innerCode = innerCode.replaceAll("import .*;", "");
                innerCode = innerCode.replaceAll("package .*;", "");
                innerCode = innerCode.replaceAll(" " + getShortName() + "." + innerSource.getShortName(),
                        " " + innerSource.getShortName());

                out.append(innerCode);
            }

            if (closeCurly != -1) {
                out.append("}\n");
            }
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:de.ub0r.android.callmeter.ui.prefs.Preferences.java

/**
 * Export data./*from w w w  .  j  a  v  a2 s.co m*/
 * 
 * @param descr
 *            description of the exported rule set
 * @param fn
 *            one of the predefined file names from {@link DataProvider}.
 */
private void exportData(final String descr, final String fn) {
    if (descr == null) {
        final EditText et = new EditText(this);
        Builder builder = new Builder(this);
        builder.setView(et);
        builder.setCancelable(true);
        builder.setTitle(R.string.export_rules_descr);
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, final int which) {
                Preferences.this.exportData(et.getText().toString(), fn);
            }
        });
        builder.show();
    } else {
        final ProgressDialog d = new ProgressDialog(this);
        d.setIndeterminate(true);
        d.setMessage(this.getString(R.string.export_progr));
        d.setCancelable(false);
        d.show();

        // run task in background
        final AsyncTask<Void, Void, String> task = // .
                new AsyncTask<Void, Void, String>() {
                    @Override
                    protected String doInBackground(final Void... params) {
                        if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) {
                            return DataProvider.backupRuleSet(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) {
                            return DataProvider.backupLogs(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) {
                            return DataProvider.backupNumGroups(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) {
                            return DataProvider.backupHourGroups(Preferences.this, descr);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final String result) {
                        Log.d(TAG, "export:\n" + result);
                        System.out.println("\n" + result);
                        d.dismiss();
                        if (result != null && result.length() > 0) {
                            Uri uri = null;
                            int resChooser = -1;
                            if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) {
                                uri = DataProvider.EXPORT_RULESET_URI;
                                resChooser = R.string.export_rules_;
                            } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) {
                                uri = DataProvider.EXPORT_LOGS_URI;
                                resChooser = R.string.export_logs_;
                            } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) {
                                uri = DataProvider.EXPORT_NUMGROUPS_URI;
                                resChooser = R.string.export_numgroups_;
                            } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) {
                                uri = DataProvider.EXPORT_HOURGROUPS_URI;
                                resChooser = R.string.export_hourgroups_;
                            }
                            final Intent intent = new Intent(Intent.ACTION_SEND);
                            intent.setType(DataProvider.EXPORT_MIMETYPE);
                            intent.putExtra(Intent.EXTRA_STREAM, uri);
                            intent.putExtra(Intent.EXTRA_SUBJECT, // .
                                    "Call Meter 3G export");
                            intent.addCategory(Intent.CATEGORY_DEFAULT);

                            try {
                                final File d = Environment.getExternalStorageDirectory();
                                final File f = new File(d, DataProvider.PACKAGE + File.separator + fn);
                                f.mkdirs();
                                if (f.exists()) {
                                    f.delete();
                                }
                                f.createNewFile();
                                FileWriter fw = new FileWriter(f);
                                fw.append(result);
                                fw.close();
                                // call an exporting app with the uri to the
                                // preferences
                                Preferences.this.startActivity(
                                        Intent.createChooser(intent, Preferences.this.getString(resChooser)));
                            } catch (IOException e) {
                                Log.e(TAG, "error writing export file", e);
                                Toast.makeText(Preferences.this, R.string.err_export_write, Toast.LENGTH_LONG)
                                        .show();
                            }
                        }
                    }
                };
        task.execute((Void) null);
    }
}

From source file:org.wso2.andes.kernel.MessageHandler.java

/**
 * Dump all message status of the slots read to file given
 *
 * @param fileToWrite      file to write
 * @param storageQueueName name of storage queue
 * @throws AndesException/*  w  w w .j  a v a2 s. c  o  m*/
 */
public void dumpAllSlotInformationToFile(File fileToWrite, String storageQueueName) throws AndesException {

    FileWriter information = null;
    try {
        information = new FileWriter(fileToWrite, true);
        for (Slot slot : slotsRead.values()) {
            List<DeliverableAndesMetadata> messagesOfSlot = slot.getAllMessagesOfSlot();
            if (!messagesOfSlot.isEmpty()) {

                int writerFlushCounter = 0;
                for (DeliverableAndesMetadata message : messagesOfSlot) {
                    information.append(storageQueueName).append(",").append(slot.getId()).append(",")
                            .append(message.dumpMessageStatus()).append("\n");
                    writerFlushCounter = writerFlushCounter + 1;
                    if (writerFlushCounter % 10 == 0) {
                        information.flush();
                    }
                }

                information.flush();
            }
        }
        information.flush();

    } catch (FileNotFoundException e) {
        log.error("File to write is not found", e);
        throw new AndesException("File to write is not found", e);
    } catch (IOException e) {
        log.error("Error while dumping message status to file", e);
        throw new AndesException("Error while dumping message status to file", e);
    } finally {
        try {
            if (information != null) {
                information.close();
            }
        } catch (IOException e) {
            log.error("Error while closing file when dumping message status to file", e);
        }
    }
}

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

/**
 * Appending an checksum archive entry to the checksum file. The record string is created and appended to the file.
 *
 * @param filename The name of the file to add.
 * @param checksum The checksum of the file to add.
 * @throws IOFailure If something is wrong when writing to the file.
 *///from w  ww.ja v  a  2 s . c  o  m
private synchronized void appendEntryToFile(String filename, String checksum) throws IOFailure {
    // initialise the record.
    String record = filename + CHECKSUM_SEPARATOR + checksum + "\n";

    // get a filewriter for the checksum file, and append the record.
    boolean appendToFile = true;

    // Synchronize to ensure that the file is not overridden during the
    // appending of the new entry.
    synchronized (checksumFile) {
        try {
            FileWriter fwrite = new FileWriter(checksumFile, appendToFile);
            try {
                fwrite.append(record);
            } finally {
                // close fileWriter.
                fwrite.flush();
                fwrite.close();
            }
        } catch (IOException e) {
            throw new IOFailure("An error occurred while appending an entry to the archive file.", e);
        }

        // The checksum file has been updated and so has its timestamp.
        // Thus update the last modified date for the checksum file.
        lastModifiedChecksumFile = checksumFile.lastModified();
    }
}

From source file:com.att.aro.main.FileTypesChartPanel.java

/**
 * Adds the file information in to provided writer.
 * /* w w  w .j  av a2 s.  c  o  m*/
 * @param writer
 * @throws IOException
 */
public void addFiletypes(FileWriter writer) throws IOException {
    StringBuffer apps = new StringBuffer();
    apps.append(rb.getString("statics.csvCell.seperator"));
    apps.append(rb.getString("simple.percent"));
    apps.append(rb.getString("statics.csvCell.seperator"));
    apps.append(rb.getString("statics.csvUnits.bytes"));
    apps.append('\n');
    for (FileTypeSummary fileType : content) {
        apps.append(fileType.getFileType());
        apps.append(rb.getString("statics.csvCell.seperator"));
        apps.append(fileType.getPct() + "%");
        apps.append(rb.getString("statics.csvCell.seperator"));
        apps.append(fileType.getBytes());
        apps.append('\n');
    }

    writer.append(apps);
}

From source file:org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl.java

private void writeConfigProperties(File file, Map<String, String> settings) throws IOException {
    FileWriter fileWriter = new FileWriter(file);

    for (Entry<String, String> entry : settings.entrySet())
        fileWriter.append(entry.getKey() + "=" + entry.getValue() + "\n");
    fileWriter.close();//  w ww.j ava2 s .c om
}

From source file:org.wso2.andes.kernel.OnflightMessageTracker.java

/**
 * Dump message info to a csv file//w  w  w. j  a  va 2  s  .co  m
 *
 * @param fileToWrite file to dump info
 * @throws AndesException
 */
public void dumpMessageStatusToFile(File fileToWrite) throws AndesException {

    try {
        FileWriter writer = new FileWriter(fileToWrite);

        writer.append("Message ID");
        writer.append(',');
        writer.append("Message Header");
        writer.append(',');
        writer.append("Destination");
        writer.append(',');
        writer.append("Message status");
        writer.append(',');
        writer.append("Slot Info");
        writer.append(',');
        writer.append("Timestamp");
        writer.append(',');
        writer.append("Expiration time");
        writer.append(',');
        writer.append("NumOfScheduledDeliveries");
        writer.append(',');
        writer.append("Channels sent");
        writer.append('\n');

        for (Long messageID : msgId2MsgData.keySet()) {
            MsgData trackingData = msgId2MsgData.get(messageID);
            writer.append(Long.toString(trackingData.msgID));
            writer.append(',');
            writer.append("null");
            writer.append(',');
            writer.append(trackingData.destination);
            writer.append(',');
            writer.append(trackingData.getStatusHistory());
            writer.append(',');
            writer.append(trackingData.slot.toString());
            writer.append(',');
            writer.append(Long.toString(trackingData.timestamp));
            writer.append(',');
            writer.append(Long.toString(trackingData.expirationTime));
            writer.append(',');
            writer.append(Integer.toString(trackingData.numberOfScheduledDeliveries.get()));
            writer.append(',');
            String deliveries = "";
            for (UUID channelID : trackingData.channelToNumOfDeliveries.keySet()) {
                deliveries = deliveries + channelID + " >> "
                        + trackingData.channelToNumOfDeliveries.get(channelID) + " : ";
            }
            writer.append(deliveries);
            writer.append('\n');
        }

        writer.flush();
        writer.close();

    } catch (FileNotFoundException e) {
        log.error("File to write is not found", e);
        throw new AndesException("File to write is not found", e);
    } catch (IOException e) {
        log.error("Error while dumping message status to file", e);
        throw new AndesException("Error while dumping message status to file", e);
    }
}