Example usage for java.io BufferedWriter append

List of usage examples for java.io BufferedWriter append

Introduction

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

Prototype

public Writer append(CharSequence csq) throws IOException 

Source Link

Document

Appends the specified character sequence to this writer.

Usage

From source file:com.termmed.statistics.db.importer.ImportManager.java

/**
 * Save new date./*from w  w  w.  jav a 2 s. c  o m*/
 *
 * @param fileName the file name
 * @param date the date
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void saveNewDate(String fileName, String date) throws IOException {
    if (!dataFolder.exists()) {
        dataFolder.mkdirs();
    }
    File file = new File(dataFolder, fileName + ".dat");
    BufferedWriter bw = getWriter(file.getAbsolutePath());
    bw.append(date);
    bw.append("\r\n");
    bw.close();
    bw = null;
}

From source file:com.matthewmitchell.peercoin_android_wallet.ui.WalletActivity.java

public void handleExportTransactions() {

    // Create CSV file from transactions

    final File file = new File(Constants.Files.EXTERNAL_WALLET_BACKUP_DIR,
            Constants.Files.TX_EXPORT_NAME + "-" + getFileDate() + ".csv");

    try {//from w w w . j  a v  a  2  s  .c  o m

        final BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.append("Date,Label,Amount (" + MonetaryFormat.CODE_PPC + "),Fee (" + MonetaryFormat.CODE_PPC
                + "),Address,Transaction Hash,Confirmations\n");

        if (txListAdapter == null || txListAdapter.transactions.isEmpty()) {
            longToast(R.string.export_transactions_mail_intent_failed);
            log.error("exporting transactions failed");
            return;
        }

        final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm z");
        dateFormat.setTimeZone(TimeZone.getDefault());

        for (Transaction tx : txListAdapter.transactions) {

            TransactionsListAdapter.TransactionCacheEntry txCache = txListAdapter.getTxCache(tx);
            String memo = tx.getMemo() == null ? "" : StringEscapeUtils.escapeCsv(tx.getMemo());
            String fee = tx.getFee() == null ? "" : tx.getFee().toPlainString();
            String address = txCache.address == null ? getString(R.string.export_transactions_unknown)
                    : txCache.address.toString();

            writer.append(dateFormat.format(tx.getUpdateTime()) + ",");
            writer.append(memo + ",");
            writer.append(txCache.value.toPlainString() + ",");
            writer.append(fee + ",");
            writer.append(address + ",");
            writer.append(tx.getHash().toString() + ",");
            writer.append(tx.getConfidence().getDepthInBlocks() + "\n");

        }

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

    } catch (IOException x) {
        longToast(R.string.export_transactions_mail_intent_failed);
        log.error("exporting transactions failed", x);
        return;
    }

    final DialogBuilder dialog = new DialogBuilder(this);
    dialog.setMessage(Html.fromHtml(getString(R.string.export_transactions_dialog_success, file)));

    dialog.setPositiveButton(WholeStringBuilder.bold(getString(R.string.export_keys_dialog_button_archive)),
            new OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, final int which) {

                    final Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_transactions_mail_subject));
                    intent.putExtra(Intent.EXTRA_TEXT,
                            makeEmailText(getString(R.string.export_transactions_mail_text)));
                    intent.setType(Constants.MIMETYPE_TX_EXPORT);
                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));

                    try {
                        startActivity(Intent.createChooser(intent,
                                getString(R.string.export_transactions_mail_intent_chooser)));
                        log.info("invoked chooser for exporting transactions");
                    } catch (final Exception x) {
                        longToast(R.string.export_transactions_mail_intent_failed);
                        log.error("exporting transactions failed", x);
                    }

                }

            });

    dialog.setNegativeButton(R.string.button_dismiss, null);
    dialog.show();

}

From source file:analysis.postRun.PostRunWindow.java

/**
 * Method which writes the text passed to the file specified.
 * @param fileName/*w  w  w .  j a  va 2 s.  c  om*/
 *                Which file to write to.
 *         text
 *                List of string arrays to write.
 */
private void writeToFile(String fileName, LinkedList<String[]> text) {
    //append text to file fileName
    try {
        BufferedWriter b = new BufferedWriter(new FileWriter(fileName));
        for (int k = 0; k < text.size(); k++) {
            for (int l = 0; l < text.get(0).length; l++) {
                b.append(text.get(k)[l]);
            }
            if (k != (text.size() - 1)) {
                b.append('\n');
            }
        }
        b.close();
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

From source file:analytics.storage.store2csv.java

@Override
public void appendRepositoryData(String repoName, int noRecords, float avgFSize, float storageReq,
        float informativeness, String schema) throws IOException {

    // TODO Auto-generated method stub
    String sFileName = "Federation" + "_GeneralInfo" + ".csv";
    ConfigureLogger conf = new ConfigureLogger();

    Properties props = new Properties();
    try {//from  www  .  j  a v a 2s .  c om
        props.load(new FileInputStream("configure.properties"));
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        System.exit(-1);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        System.exit(-1);
    }
    ;
    File anls = new File(props.getProperty(AnalyticsConstants.resultsPath) + "Analysis_Results");

    if (!anls.exists())
        anls.mkdir();

    File dir = new File(anls, "Federation");
    if (!dir.exists())
        dir.mkdir();

    File file = new File(dir, sFileName);

    if (!file.exists())
        file.createNewFile();

    Logger logger = conf.getLogger("generalInfo", anls + File.separator + "repoGeneralInfo.log");

    StringBuffer logString = new StringBuffer();

    FileWriter writer;
    BufferedWriter bw = null;
    try {
        writer = new FileWriter(file, true);
        bw = new BufferedWriter(writer);

        if (!isAppendData()) {

            setAppend(true);
            // create header
            bw.append("Repository Name");

            bw.append(",");
            bw.append("Number of records");
            bw.append(",");
            bw.append("Average file size(bytes)");
            bw.append(",");
            bw.append("Approximate Storage requirements(bytes)");
            bw.append(",");
            bw.append("AVG informativeness(bits)");
            bw.append(",");
            bw.append("Metadata schema namespace");
            bw.newLine();
            bw.append(repoName);
            logString.append(repoName);
            bw.append(",");
            bw.append(String.valueOf(noRecords));
            logString.append(" " + String.valueOf(noRecords));
            bw.append(",");
            bw.append(String.valueOf(avgFSize));
            logString.append(" " + String.valueOf(avgFSize));
            bw.append(",");
            bw.append(String.valueOf(storageReq));
            logString.append(" " + String.valueOf(storageReq));
            bw.append(",");
            bw.append(String.valueOf(informativeness));
            logString.append(" " + String.valueOf(informativeness));
            bw.append(",");
            bw.append(schema);
            logString.append(" " + String.valueOf(schema));
            bw.newLine();
            bw.close();

        } else {
            // insert data
            bw.append(repoName);
            logString.append(repoName);
            bw.append(",");
            bw.append(String.valueOf(noRecords));
            logString.append(" " + String.valueOf(noRecords));
            bw.append(",");
            bw.append(String.valueOf(avgFSize));
            logString.append(" " + String.valueOf(avgFSize));
            bw.append(",");
            bw.append(String.valueOf(storageReq));
            logString.append(" " + String.valueOf(storageReq));
            bw.append(",");
            bw.append(String.valueOf(informativeness));
            logString.append(" " + String.valueOf(informativeness));
            bw.append(",");
            bw.append(schema);
            logString.append(" " + String.valueOf(schema));
            bw.newLine();
            bw.close();
        }
        logger.info(logString.toString());

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            if (bw != null)
                bw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}

From source file:com.termmed.statistics.db.importer.ImportManager.java

/**
 * Gets the descriptions for top level.//from   www. ja  v a2s  .co  m
 *
 * @param txtFile the txt file
 * @return the descriptions for top level
 * @throws Exception the exception
 */
private void getDescriptionsForTopLevel(File txtFile) throws Exception {
    String descFile;
    if (releaseDependencies) {
        descFile = CurrentFile.get().getCompleteDescriptionSnapshot();
    } else {
        descFile = CurrentFile.get().getSnapshotDescriptionFile();
    }
    BufferedReader br = FileHelper.getReader(txtFile);
    String header = br.readLine();
    String line;
    String[] spl;
    HashMap<String, String> mapTopLevel = new HashMap<String, String>();
    while ((line = br.readLine()) != null) {
        spl = line.split("\t", -1);
        mapTopLevel.put(spl[0], "");
    }
    br.close();
    br = FileHelper.getReader(descFile);
    br.readLine();
    while ((line = br.readLine()) != null) {
        spl = line.split("\t", -1);
        if (spl[2].equals("1") && mapTopLevel.containsKey(spl[4])) {
            String tmp = mapTopLevel.get(spl[4]);
            if (tmp.equals("")) {
                mapTopLevel.put(spl[4], spl[7]);
            } else if (spl[6].equals("900000000000003001")) {
                mapTopLevel.put(spl[4], spl[7]);
            }
        }
    }

    br.close();
    BufferedWriter bw = FileHelper.getWriter(txtFile);
    bw.append(header);
    bw.append("\r\n");
    for (String key : mapTopLevel.keySet()) {
        bw.append(key);
        bw.append("\t");
        bw.append(mapTopLevel.get(key));
        bw.append("\r\n");

    }
    bw.close();
}

From source file:org.gwaspi.statistics.ChiSqrBoundaryCalculator.java

protected static void calculateChisqrBoundaryByStDev() throws IOException, MathException {

    FileWriter repFW = new FileWriter(boundaryPath);
    BufferedWriter repBW = new BufferedWriter(repFW);

    NetcdfFile ncfile = NetcdfFile.open(netCDFFile);
    List<Dimension> dims = ncfile.getDimensions();
    Dimension sizeDim = dims.get(0);
    Dimension simsDim = dims.get(1);

    String varName = "distributions";
    Variable distributions = ncfile.findVariable(varName);

    try {/*from ww w  .j  av  a 2  s. c om*/
        for (int i = 0; i < pointsNb; i++) {
            //distributions(i:i:1, 0:simsNb:1)
            ArrayDouble.D2 rdDoubleArrayD2 = (ArrayDouble.D2) distributions
                    .read(i + ":" + i + ":1, 0:" + (simsDim.getLength() - 1) + ":1");
            ArrayDouble.D1 rdDoubleArrayD1 = (D1) rdDoubleArrayD2.reduce();

            double sampleSize = rdDoubleArrayD2.getSize();
            double currentTot = 0;

            double[] allValues = new double[(int) sampleSize];
            for (int j = 0; j < sampleSize; j++) {
                allValues[j] = rdDoubleArrayD1.get(j);
                currentTot += rdDoubleArrayD1.get(j);
            }

            StandardDeviation stdDev = new StandardDeviation();
            double stdDevValue = stdDev.evaluate(allValues);

            double currentAvg = currentTot / simNb;

            double low95 = currentAvg - (2 * stdDevValue); // Display 2 standard deviations
            double top95 = currentAvg + (2 * stdDevValue); // Display 2 standard deviations

            StringBuilder sb = new StringBuilder();
            sb.append(top95);
            sb.append(",");
            sb.append(currentAvg);
            sb.append(",");
            sb.append(low95);
            repBW.append(sb + "\n");
        }
    } catch (IOException ex) {
        log.error("Cannot read data", ex);
    } catch (InvalidRangeException ex) {
        log.error("Cannot read data", ex);
    }

    repBW.close();
    repFW.close();

    log.info("Confidence boundary created for {} points", N);
}

From source file:edu.uchc.octane.OctaneWindowControl.java

/**
 * Export selected trajectories to text.
 * Each molecule occupy one line: frame, x, y, z, height, trackIdx
 * // w w w .  j a  va 2s. co  m
 * @param file the file
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void exportTrajectories(File file) throws IOException {

    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    int[] selected = frame_.getTrajsTable().getSelectedTrajectories();
    Trajectory traj;
    bw.append("# Frame, X, Y, Z, Intensity, TrackIDX\n");

    for (int i = 0; i < selected.length; i++) {

        traj = dataset_.getTrajectoryByIndex(selected[i]);

        for (int j = 0; j < traj.size(); j++) {

            SmNode n = traj.get(j);
            bw.append(n.toString());
            bw.append(", " + i + "\n");

        }
    }

    bw.close();
}

From source file:de.tudarmstadt.ukp.clarin.webanno.automation.util.AutomationUtil.java

public static void addOtherFeatureTrainDocument(MiraTemplate aTemplate, RepositoryService aRepository,
        AnnotationService aAnnotationService, AutomationService aAutomationService, UserDao aUserDao)
        throws IOException, UIMAException, ClassNotFoundException {
    File miraDir = aAutomationService.getMiraDir(aTemplate.getTrainFeature());
    if (!miraDir.exists()) {
        FileUtils.forceMkdir(miraDir);/*from   ww  w  . j  a va2 s. co m*/
    }

    AutomationStatus status = aAutomationService.getAutomationStatus(aTemplate);
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    User user = aUserDao.get(username);
    for (AnnotationFeature feature : aTemplate.getOtherFeatures()) {
        File trainFile = new File(miraDir, feature.getId() + ".train");
        boolean documentChanged = false;
        for (SourceDocument document : aRepository.listSourceDocuments(feature.getProject())) {
            if (!document.isProcessed()
                    && (document.getFeature() != null && document.getFeature().equals(feature))) {
                documentChanged = true;
                break;
            }
        }
        if (!documentChanged && trainFile.exists()) {
            continue;
        }

        BufferedWriter trainOut = new BufferedWriter(new FileWriter(trainFile));
        AutomationTypeAdapter adapter = (AutomationTypeAdapter) TypeUtil.getAdapter(aAnnotationService,
                feature.getLayer());
        for (SourceDocument sourceDocument : aRepository.listSourceDocuments(feature.getProject())) {
            if ((sourceDocument.isTrainingDocument() && sourceDocument.getFeature() != null
                    && sourceDocument.getFeature().equals(feature))) {
                JCas jCas = aRepository.readAnnotationCas(sourceDocument, user);
                for (Sentence sentence : select(jCas, Sentence.class)) {
                    trainOut.append(getMiraLine(sentence, feature, adapter).toString() + "\n");
                }
                sourceDocument.setProcessed(false);
                status.setTrainDocs(status.getTrainDocs() - 1);
            }

        }
        trainOut.close();
    }
}

From source file:com.termmed.statistics.Processor.java

private void printInternPriorityList(IReportDetail file, HashSet<Long> conceptList, File outputFold)
        throws IOException {
    File exclFile = new File(I_Constants.EXCLUYENT_OUTPUT_FOLDER + "/" + file.getFile()
            + (file.getFile().toLowerCase().endsWith(".csv") ? "" : ".csv"));
    File completeDetailFile = new File(I_Constants.STATS_OUTPUT_FOLDER + "/" + file.getFile()
            + (file.getFile().toLowerCase().endsWith(".csv") ? "" : ".csv"));
    TreeSet<Long> order = getOrder(file, completeDetailFile);
    BufferedWriter bw = FileHelper.getWriter(exclFile);
    Integer sctIdIndex = file.getSctIdIndex();
    if (sctIdIndex == null) {
        sctIdIndex = 1;/*from   w  w w. j  a v  a2 s  .  co m*/
    }
    Integer priorityIndex = file.getPriorityListColumnIndex();
    if (priorityIndex == null) {
        priorityIndex = 5;
    }
    boolean first = true;
    String line;
    String[] spl;

    for (Long ord : order) {
        BufferedReader br = FileHelper.getReader(completeDetailFile);
        if (first) {
            bw.append(br.readLine());
            bw.append("\r\n");
            first = false;
        } else {
            br.readLine();
        }

        while ((line = br.readLine()) != null) {
            spl = line.split(",", -1);
            Long prior = Long.parseLong(spl[priorityIndex]);
            if (!prior.equals(ord)) {
                continue;
            }
            Long cid = Long.parseLong(spl[sctIdIndex]);
            if (conceptList.contains(cid)) {
                continue;
            }
            bw.append(line);
            bw.append("\r\n");
            conceptList.add(cid);
        }

        br.close();
    }
    bw.close();

}