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:ubic.gemma.loader.protein.biomart.BiomartEnsemblNcbiFetcher.java

/**
 * Method reads data returned from biomart and writes to file adding a header containing the queried attributes.
 * // w ww .ja v  a2  s . c om
 * @param biomartTaxonName Taxon name configured for biomart
 * @param reader The reader for reading data returned from biomart
 * @return File the biomart data written to file
 * @throws IOException Problem writing to file
 */
private File writeFile(File file, String headerForFile, BufferedReader reader) throws IOException {

    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    writer.append(headerForFile + "\n");
    String line;
    while ((line = reader.readLine()) != null) {
        if (line.contains("ERROR") && line.contains("Exception")) {
            throw new IOException("Error from BioMart: " + line);
        }
        writer.append(line + "\n");
    }
    writer.close();
    reader.close();
    return file;

}

From source file:org.ihtsdo.classifier.CycleCheck.java

/**
 * Save conceptIds in detected cycles file.
 *
 * @throws java.io.IOException Signals that an I/O exception has occurred.
 *///from   w  w w  .  j av a  2s.c o  m
private void saveDetectedCyclesFile() throws IOException {
    FileOutputStream fos = new FileOutputStream(outputFile);
    OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
    BufferedWriter bw = new BufferedWriter(osw);

    bw.append("conceptId");
    bw.append("\r\n");

    for (Long concept : conceptInLoop) {
        bw.append(concept.toString());
        bw.append("\r\n");
    }
    bw.close();
    bw = null;
    fos = null;
    osw = null;

}

From source file:de.clusteval.data.dataset.generator.Gaussian2DDataSetGenerator.java

@Override
protected GoldStandard generateGoldStandard() throws GoldStandardGenerationException {
    try {/*from   w  w w  .  j a  v  a  2 s  .  c o  m*/
        // goldstandard file
        File goldStandardFile = new File(FileUtils.buildPath(this.repository.getBasePath(GoldStandard.class),
                this.getFolderName(), this.getFileName()));
        BufferedWriter writer = new BufferedWriter(new FileWriter(goldStandardFile));
        for (int row = 0; row < classes.length; row++) {
            writer.append((row + 1) + "\t" + classes[row] + ":1.0");
            writer.newLine();
        }
        writer.close();

        return new GoldStandard(repository, goldStandardFile.lastModified(), goldStandardFile);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (RegisterException e) {
        e.printStackTrace();
    }
    throw new GoldStandardGenerationException("The goldstandard could not be generated!");
}

From source file:com.codecrate.webstart.GenerateJnlpMojo.java

private void addLine(BufferedWriter writer, String string) throws IOException {
    writer.append(string);
    writer.newLine();
}

From source file:org.torproject.ernie.db.BridgeSnapshotReader.java

public BridgeSnapshotReader(BridgeDescriptorParser bdp, String bridgeDirectoriesDir) {
    Logger logger = Logger.getLogger(BridgeSnapshotReader.class.getName());
    SortedSet<String> parsed = new TreeSet<String>();
    File bdDir = new File(bridgeDirectoriesDir);
    File pbdFile = new File("stats/parsed-bridge-directories");
    boolean modified = false;
    if (bdDir.exists()) {
        if (pbdFile.exists()) {
            logger.fine("Reading file " + pbdFile.getAbsolutePath() + "...");
            try {
                BufferedReader br = new BufferedReader(new FileReader(pbdFile));
                String line = null;
                while ((line = br.readLine()) != null) {
                    parsed.add(line);//from  w w w .j  a  v  a2  s . co m
                }
                br.close();
                logger.fine("Finished reading file " + pbdFile.getAbsolutePath() + ".");
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed reading file " + pbdFile.getAbsolutePath() + "!", e);
                return;
            }
        }
        logger.fine("Importing files in directory " + bridgeDirectoriesDir + "/...");
        Stack<File> filesInInputDir = new Stack<File>();
        filesInInputDir.add(bdDir);
        while (!filesInInputDir.isEmpty()) {
            File pop = filesInInputDir.pop();
            if (pop.isDirectory()) {
                for (File f : pop.listFiles()) {
                    filesInInputDir.add(f);
                }
            } else if (!parsed.contains(pop.getName())) {
                try {
                    FileInputStream in = new FileInputStream(pop);
                    if (in.available() > 0) {
                        GzipCompressorInputStream gcis = new GzipCompressorInputStream(in);
                        TarArchiveInputStream tais = new TarArchiveInputStream(gcis);
                        BufferedInputStream bis = new BufferedInputStream(tais);
                        String fn = pop.getName();
                        String dateTime = fn.substring(11, 21) + " " + fn.substring(22, 24) + ":"
                                + fn.substring(24, 26) + ":" + fn.substring(26, 28);
                        while ((tais.getNextTarEntry()) != null) {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            int len;
                            byte[] data = new byte[1024];
                            while ((len = bis.read(data, 0, 1024)) >= 0) {
                                baos.write(data, 0, len);
                            }
                            byte[] allData = baos.toByteArray();
                            if (allData.length == 0) {
                                continue;
                            }
                            String ascii = new String(allData, "US-ASCII");
                            BufferedReader br3 = new BufferedReader(new StringReader(ascii));
                            String firstLine = null;
                            while ((firstLine = br3.readLine()) != null) {
                                if (firstLine.startsWith("@")) {
                                    continue;
                                } else {
                                    break;
                                }
                            }
                            if (firstLine.startsWith("r ")) {
                                bdp.parse(allData, dateTime, false);
                            } else {
                                int start = -1, sig = -1, end = -1;
                                String startToken = firstLine.startsWith("router ") ? "router " : "extra-info ";
                                String sigToken = "\nrouter-signature\n";
                                String endToken = "\n-----END SIGNATURE-----\n";
                                while (end < ascii.length()) {
                                    start = ascii.indexOf(startToken, end);
                                    if (start < 0) {
                                        break;
                                    }
                                    sig = ascii.indexOf(sigToken, start);
                                    if (sig < 0) {
                                        break;
                                    }
                                    sig += sigToken.length();
                                    end = ascii.indexOf(endToken, sig);
                                    if (end < 0) {
                                        break;
                                    }
                                    end += endToken.length();
                                    byte[] descBytes = new byte[end - start];
                                    System.arraycopy(allData, start, descBytes, 0, end - start);
                                    bdp.parse(descBytes, dateTime, false);
                                }
                            }
                        }
                    }
                    in.close();

                    /* Let's give some memory back, or we'll run out of it. */
                    System.gc();

                    parsed.add(pop.getName());
                    modified = true;
                } catch (IOException e) {
                    logger.log(Level.WARNING, "Could not parse bridge snapshot " + pop.getName() + "!", e);
                    continue;
                }
            }
        }
        logger.fine("Finished importing files in directory " + bridgeDirectoriesDir + "/.");
        if (!parsed.isEmpty() && modified) {
            logger.fine("Writing file " + pbdFile.getAbsolutePath() + "...");
            try {
                pbdFile.getParentFile().mkdirs();
                BufferedWriter bw = new BufferedWriter(new FileWriter(pbdFile));
                for (String f : parsed) {
                    bw.append(f + "\n");
                }
                bw.close();
                logger.fine("Finished writing file " + pbdFile.getAbsolutePath() + ".");
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed writing file " + pbdFile.getAbsolutePath() + "!", e);
            }
        }
    }
}

From source file:org.bireme.interop.fromJson.Json2File.java

@Override
public void exportDocuments(final Iterable<JSONObject> it, final int tell) {
    if (it == null) {
        throw new NullPointerException("it");
    }//from www  . java  2s  . c o m
    if (tell <= 0) {
        throw new IllegalArgumentException("tell <= 0");
    }
    BufferedWriter writer = null;
    int tot = 0;

    try {
        if (oneFileOnly) {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), encoding));
            writer.append("[\n");
        }
        for (JSONObject obj : it) {
            if (++tot % tell == 0) {
                System.out.println("+++" + tot);
            }
            if (oneFileOnly) {
                if (tot > 1) {
                    writer.append(",");
                }
            } else {
                writer = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(renameFile(outFile, ++current)), encoding));
            }
            writer.append(obj.toString(2));
            writer.append("\n");
            if (!oneFileOnly) {
                writer.close();
            }
        }
        if (oneFileOnly) {
            writer.append("]");
            writer.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Json2File.class.getName()).log(Level.SEVERE, null, ex);
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException ex2) {
                Logger.getLogger(Json2File.class.getName()).log(Level.SEVERE, null, ex2);
            }
        }
    }
}

From source file:org.stormcat.jvbeans.sample.task.StoredDataTask.java

public void doExecute() {
    JvReader<HorseRaceInfoDto> reader = jvLinkManager.open(StoredDataResolver._RACE()._SE(), "20100601000000",
            DataOption.STANDARD);//from w  w w.  j av a 2s .com

    BufferedWriter writer = BufferedWriterUtil.getWriter("test_SE.txt", Charset.MS932);
    for (HorseRaceInfoDto dto : reader) {
        String data = dto.toString();
        if (StringUtil.isNotBlank(data)) {
            System.out.println(data);
            try {
                writer.append(data);
                writer.append("\r\n");
            } catch (IOException e) {
                throw new IORuntimeException(e);
            }
        }
    }

    IOUtils.closeQuietly(writer);
}

From source file:com.technophobia.substeps.report.DefaultExecutionReportBuilder.java

/**
 * @param stats/*  ww  w .  j  a  v  a  2 s . co  m*/
 * @param writer
 */
private void buildStatsJSON(final ExecutionStats stats, final BufferedWriter writer) throws IOException {

    writer.append("var featureStatsData = [");
    boolean first = true;

    for (final TestCounterSet stat : stats.getSortedList()) {

        if (!first) {
            writer.append(",\n");
        }
        writer.append("[\"").append(stat.getTag()).append("\",");
        writer.append("\"").append(Integer.toString(stat.getFeatureStats().getCount())).append("\",");
        writer.append("\"").append(Integer.toString(stat.getFeatureStats().getRun())).append("\",");
        writer.append("\"").append(Integer.toString(stat.getFeatureStats().getPassed())).append("\",");
        writer.append("\"").append(Integer.toString(stat.getFeatureStats().getFailed())).append("\",");
        writer.append("\"").append(Double.toString(stat.getFeatureStats().getSuccessPc())).append("\"]");

        first = false;
    }

    writer.append("];\n");

    writer.append("var scenarioStatsData = [");
    first = true;

    for (final TestCounterSet stat : stats.getSortedList()) {

        if (!first) {
            writer.append(",\n");
        }
        writer.append("[\"").append(stat.getTag()).append("\",");
        writer.append("\"").append(Integer.toString(stat.getScenarioStats().getCount())).append("\",");
        writer.append("\"").append(Integer.toString(stat.getScenarioStats().getRun())).append("\",");
        writer.append("\"").append(Integer.toString(stat.getScenarioStats().getPassed())).append("\",");
        writer.append("\"").append(Integer.toString(stat.getScenarioStats().getFailed())).append("\",");
        writer.append("\"").append(Double.toString(stat.getScenarioStats().getSuccessPc())).append("\"")
                .append("]");

        first = false;
    }

    writer.append("];\n");

}

From source file:weatherwebscraper.WeatherWebScraper.java

public void ParseDateToCSV(Date date) {

    System.out.println("Starting data scrape for " + getDayFromDate(date) + "...");

    ParsingDataThread[] threadList = new ParsingDataThread[iterations];

    long UNIXTime = (date.getTime() / 1000);

    //start timer
    Timer timer = new Timer();
    //read data from site

    for (int i = 0; i < iterations; i++) {

        threadList[i] = new ParsingDataThread(UNIXTime);
        threadList[i].start();//from  ww w  .ja  v  a  2  s.  c o  m

        //add 1/2 hour to UNIX time
        UNIXTime += 60 * 30;
    }

    //check all threads are finished
    waitForThreadPoolCompletion(threadList);

    //measure time elapsed
    timer.printTimeElapsedMessage("Data parsing");

    //start new thread list and get coarse geo data
    ParsingGeoDataThread[] geoThreadList = new ParsingGeoDataThread[data.values().size()];

    int j = 0;

    for (WindDataCollection windCollection : data.values()) {
        geoThreadList[j] = new ParsingGeoDataThread(windCollection.owner, windCollection.ownerID);
        geoThreadList[j].start();
        j++;
    }

    //check all threads are finished
    waitForThreadPoolCompletion(geoThreadList);

    timer.printTimeElapsedMessage("Coarse geo data parsing");

    //parse data to CSV
    try {
        String filePath = System.getProperty("user.dir") + "\\" + getDayFromDate(date) + ".csv";
        File f = new File(filePath);
        BufferedWriter writer = new BufferedWriter(new FileWriter(f));

        //write column titles
        writer.append(String.format(
                "Station Name, Latitude, Longitude%s, Speed Units,\t UNIX Time, Wind Direction, Wind Speed Lo (%s), Wind Speed Hi (%s), Gust Speed (%s)",
                useGoogleLocationData
                        ? ", number of locations returned by Google, distance between coarse and Google coordinates (m)"
                        : "",
                dataUnits, dataUnits, dataUnits));
        writer.newLine();

        ArrayList<WindDataCollection> dataList = new ArrayList(data.values());

        //sort data collections by name
        Collections.sort(dataList);

        for (WindDataCollection collection : dataList) {
            writer.append(collection.owner + ",");

            if (useGoogleLocationData) {
                String trimmedOwner = collection.owner.substring(0, collection.owner.lastIndexOf("(") - 1);

                //get fine geo data from Google
                double[] latLong = GoogleMapsQuery.getClosestLatLong(trimmedOwner,
                        geoData.get(collection.owner).get(0).toString(),
                        geoData.get(collection.owner).get(1).toString(), distanceThreshold);

                if (latLong != null) {
                    writer.append(latLong[0] + ",");
                    writer.append(latLong[1] + ",");
                    writer.append(latLong[3] + ",");
                    writer.append(latLong[2] + ",");
                } else {
                    writer.append(",,,,,");
                }
            } else {
                writer.append(geoData.get(collection.owner).get(0) + ",");
                writer.append(geoData.get(collection.owner).get(1) + ",");
            }

            writer.append(dataUnits);

            Collections.sort(collection.points);
            writer.append("\t");

            for (WindDataPoint point : collection.points) {
                writer.append(point.time + ",");
                writer.append(point.direction + ",");
                writer.append(point.speedLo + ",");
                writer.append(point.speedHi + ",");
                writer.append(point.gust + "\t");
            }
            writer.newLine();
        }

        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    timer.printTimeElapsedMessage("Data writing");
    timer.printTotalTimeElapsed();
    System.out.println("Done.");
}

From source file:com.sludev.commons.vfs2.provider.azure.AzFileProviderTest.java

/**
 * //from w  w w.j a  va  2 s.c o  m
 */
@Test
public void A001_uploadFile() throws Exception {
    String currAccountStr = testProperties.getProperty("azure.account.name");
    String currKey = testProperties.getProperty("azure.account.key");
    String currContainerStr = testProperties.getProperty("azure.test0001.container.name");
    String currHost = testProperties.getProperty("azure.host"); // <account>.blob.core.windows.net
    String currFileNameStr;

    File temp = File.createTempFile("uploadFile01", ".tmp");
    try (FileWriter fw = new FileWriter(temp)) {
        BufferedWriter bw = new BufferedWriter(fw);
        bw.append("testing...");
        bw.flush();
    }

    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(AzConstants.AZSBSCHEME, new AzFileProvider());
    currMan.addProvider("file", new DefaultLocalFileProvider());
    currMan.init();

    StaticUserAuthenticator auth = new StaticUserAuthenticator("", currAccountStr, currKey);
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    currFileNameStr = "test01.tmp";
    String currUriStr = String.format("%s://%s/%s/%s", AzConstants.AZSBSCHEME, currHost, currContainerStr,
            currFileNameStr);
    FileObject currFile = currMan.resolveFile(currUriStr, opts);
    FileObject currFile2 = currMan.resolveFile(String.format("file://%s", temp.getAbsolutePath()));

    currFile.copyFrom(currFile2, Selectors.SELECT_SELF);
    temp.delete();
}