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.codesourcery.installer.actions.EnvironmentAction.java

/**
 * Handles Linux path environment.// w ww .  j  a v  a 2  s .c  om
 * 
 * @param product Product
 * @param mode Mode
 * @param monitor Progress monitor
 * @throws CoreException on failure
 */
private void runLinux(IInstallProduct product, IInstallMode mode, IProgressMonitor monitor)
        throws CoreException {
    // Path to .profile
    String homeDir = System.getProperty("user.home");
    if (homeDir == null)
        Installer.fail("Failed to get user home directory.");
    IPath homePath = new Path(homeDir);

    // Check for profile
    String profileFilename = null;
    File profileFile = null;
    for (String name : PROFILE_FILENAMES) {
        IPath profilePath = homePath.append(name);
        profileFile = profilePath.toFile();
        if (profileFile.exists()) {
            profileFilename = name;
            break;
        } else {
            Installer.log(name + " not found, skipping.");
        }
    }
    if (profileFilename == null) {
        // Create a new profile.
        profileFilename = PROFILE_FILENAMES[PROFILE_DEFAULT_INDEX];
        IPath newProfilePath = homePath.append(profileFilename);
        try {
            profileFile = newProfilePath.toFile();
            profileFile.createNewFile();
        } catch (IOException e) {
            Installer.log("Could not create profile " + newProfilePath);
            return;
        }
    }

    // Do not modify read-only profile
    if (!profileFile.canWrite()) {
        Installer.log("Profile was not modified because it is read-only.");
        return;
    }

    // File date suffix
    SimpleDateFormat fileDateFormat = new SimpleDateFormat("yyyyDDDHHmmss");
    String fileDateDesc = fileDateFormat.format(new Date());
    // Backup file path
    String backupName = profileFilename + fileDateDesc;
    IPath backupPath = homePath.append(backupName);
    File backupFile = backupPath.toFile();

    String line;
    // Install
    if (mode.isInstall()) {
        // Date description
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");
        String dateDesc = dateFormat.format(new Date());

        // Make backup of .profile
        try {
            org.apache.commons.io.FileUtils.copyFile(profileFile, backupFile);
        } catch (IOException e) {
            Installer.fail(InstallMessages.Error_FailedToBackupProfile, e);
        }

        // Write path extensions
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(profileFile, true));
            writer.newLine();
            // Write product block start
            writer.append(getProfileMarker(product, true));
            writer.newLine();
            writer.append("# Do NOT modify these lines; they are used to uninstall.");
            writer.newLine();
            line = MessageFormat.format("# New environment added by {0} on {1}.",
                    new Object[] { product.getName(), dateDesc });
            writer.append(line);
            writer.newLine();
            line = MessageFormat.format("# The unmodified version of this file is saved in {0}.",
                    backupPath.toOSString());
            writer.append(line);
            writer.newLine();

            monitor.setTaskName("Setting environment variables...");
            for (EnvironmentVariable environmentVariable : environmentVariables) {
                monitor.setTaskName(
                        NLS.bind(InstallMessages.SettingEnvironment, environmentVariable.getName()));
                StringBuilder buffer = new StringBuilder();
                buffer.append(environmentVariable.getName());
                buffer.append('=');
                // Append variable
                if (environmentVariable.getOperation() == EnvironmentOperation.APPEND) {
                    buffer.append("${");
                    buffer.append(environmentVariable.getName());
                    buffer.append("}");
                    buffer.append(environmentVariable.getDelimiter());
                }
                boolean path = "PATH".equals(environmentVariable.getName());
                if (path)
                    buffer.append('\"');
                buffer.append(environmentVariable.getValue());
                if (path)
                    buffer.append('\"');
                if (environmentVariable.getOperation() == EnvironmentOperation.PREPEND) {
                    buffer.append(environmentVariable.getDelimiter());
                    buffer.append("${");
                    buffer.append(environmentVariable.getName());
                    buffer.append("}");
                }
                writer.append(buffer.toString());
                writer.newLine();
                writer.append("export ");
                writer.append(environmentVariable.getName());
                writer.newLine();
            }

            // Write product block end
            writer.append(getProfileMarker(product, false));
            writer.newLine();

        } catch (IOException e) {
            Installer.fail(InstallMessages.Error_FailedToUpdateProfile, e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
        }
    }
    // Uninstall
    else {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        boolean inProductBlock = false;
        try {
            reader = new BufferedReader(new FileReader(profileFile));
            writer = new BufferedWriter(new FileWriter(backupFile));
            while ((line = reader.readLine()) != null) {
                // Start of product path block
                if (line.startsWith(getProfileMarker(product, true))) {
                    inProductBlock = true;
                }
                // End of product path block
                else if (line.startsWith(getProfileMarker(product, false))) {
                    inProductBlock = false;
                }
                // If not in product path block, copy lines
                else if (!inProductBlock) {
                    writer.write(line);
                    writer.newLine();
                }
            }
        } catch (IOException e) {
            Installer.fail(InstallMessages.Error_FailedToUpdateProfile, e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
        }

        // Copy new profile
        try {
            org.apache.commons.io.FileUtils.copyFile(backupFile, profileFile);
        } catch (IOException e) {
            Installer.fail(InstallMessages.Error_FailedToUpdateProfile, e);
        }

        backupFile.delete();
    }
}

From source file:org.ihtsdo.statistics.Processor.java

/**
 * Prints the report.//from w w w.  jav a2  s .c o m
 *
 * @param bw the bw
 * @param detail the detail
 * @throws Exception the exception
 */
private void printReport(BufferedWriter bw, OutputDetailFile detail) throws Exception {

    SQLStatementExecutor executor = new SQLStatementExecutor(connection);

    for (StoredProcedure sProc : detail.getStoredProcedure()) {
        executor.executeStoredProcedure(sProc, ImportManager.params, null);
        ResultSet rs = executor.getResultSet();
        if (rs != null) {
            ResultSetMetaData meta = rs.getMetaData();
            while (rs.next()) {
                for (int i = 0; i < meta.getColumnCount(); i++) {
                    Object obj = rs.getObject(i + 1);
                    if (obj != null) {
                        bw.append(obj.toString().replaceAll(",", "&#44;").trim());
                    } else {
                        bw.append("missing_data");
                    }
                    if (i + 1 < meta.getColumnCount()) {
                        bw.append(",");
                    } else {
                        bw.append("\r\n");
                    }
                }
            }
            meta = null;
            rs.close();
        }

    }
    executor = null;
}

From source file:analytics.storage.store2csv.java

@Override
public void storeRepositoryData(String repoName, int noRecords, float avgFSize, float storageReq,
        float informativeness, String schema) {
    // TODO Auto-generated method stub

    ConfigureLogger conf = new ConfigureLogger();

    String sFileName = repoName + "_GeneralInfo" + ".csv";

    Properties props = new Properties();
    try {//from   w  ww. jav a2  s .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, repoName);
    if (!dir.exists())
        dir.mkdir();

    File file = new File(dir, sFileName);

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

    StringBuffer logString = new StringBuffer();

    this.setGeneralDataFilePath(file.getAbsolutePath());
    FileWriter writer;
    BufferedWriter bw = null;
    try {
        writer = new FileWriter(file);
        bw = new BufferedWriter(writer);
        // 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("Repository Informativeness(bits)");
        bw.append(",");
        bw.append("Metadata schema namespace");
        bw.newLine();

        // 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(" " + schema);
        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:org.dkpro.tc.ml.liblinear.LiblinearDataWriter.java

@Override
public void write(File outputDirectory, FeatureStore featureStore, boolean useDenseInstances,
        String learningMode, boolean applyWeighting) throws Exception {
    FeatureNodeArrayEncoder encoder = new FeatureNodeArrayEncoder();
    FeatureNode[][] nodes = encoder.featueStore2FeatureNode(featureStore);

    String fileName = LiblinearAdapter.getInstance()
            .getFrameworkFilename(AdapterNameEntries.featureVectorsFile);
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(new File(outputDirectory, fileName)), "utf-8"));

    Map<String, String> index2instanceId = new HashMap<>();

    for (int i = 0; i < nodes.length; i++) {
        Instance instance = featureStore.getInstance(i);

        recordInstanceId(instance, i, index2instanceId);

        List<String> elements = new ArrayList<String>();
        for (int j = 0; j < nodes[i].length; j++) {
            FeatureNode node = nodes[i][j];
            int index = node.getIndex();
            double value = node.getValue();

            // write sparse values, i.e. skip zero values
            if (Math.abs(value) > 0.00000000001) {
                elements.add(index + ":" + value);
            }/*from   w  w  w.  j a va  2 s. c  o  m*/
        }
        bw.append(instance.getOutcome());
        bw.append("\t");
        bw.append(StringUtils.join(elements, "\t"));
        bw.append("\n");
    }
    bw.close();

    //write mapping
    writeMapping(outputDirectory, INDEX2INSTANCEID, index2instanceId);
}

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

protected static void calculateChisqrBoundaryByVariance() 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 {// w  ww.  ja  v  a  2  s . c o m
        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);
            }

            Variance variance = new Variance();
            double varianceValue = variance.evaluate(allValues);

            double currentAvg = currentTot / simNb;

            double low95 = currentAvg - varianceValue;
            double top95 = currentAvg + varianceValue;

            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:org.pentaho.telemetry.serializers.EventSerializerCSV.java

protected boolean serializeEventsToFile(String fileName, List<TelemetryEvent> events) {

    BufferedWriter bw = null;
    try {//w ww.  j a  va 2 s.c  om
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"));
    } catch (FileNotFoundException ex) {
        logger.error("Unable to open file for writing. FileName: " + fileName, ex);
        return false;
    } catch (UnsupportedEncodingException ex) {
        logger.error("Unsupported encoding UTF-8?", ex);
        return false;
    }

    StringBuilder line = new StringBuilder();

    line.append("pluginName").append(CSV_SEPARATOR).append("pluginVersion").append(CSV_SEPARATOR)
            .append("platformVersion").append(CSV_SEPARATOR).append("timestamp").append(CSV_SEPARATOR)
            .append("type").append(CSV_SEPARATOR).append("origin").append(CSV_SEPARATOR).append("extraInfo");

    try {
        bw.append(line.toString());
        bw.newLine();

        for (TelemetryEvent te : events) {
            line.delete(0, line.length());

            line.append(safeCsvString(te.getPluginName())).append(CSV_SEPARATOR)
                    .append(safeCsvString(te.getPluginVersion())).append(CSV_SEPARATOR)
                    .append(safeCsvString(te.getPlatformVersion())).append(CSV_SEPARATOR)
                    .append(te.getEventTimestamp()).append(CSV_SEPARATOR).append(te.getEventType().name())
                    .append(CSV_SEPARATOR).append(safeCsvString(te.getOrigin())).append(CSV_SEPARATOR)
                    .append(safeCsvString(getExtraInfoAsString(te.getExtraInfo())));

            bw.append(line.toString());
            bw.newLine();
        }

        bw.flush();
        bw.close();
    } catch (IOException ioe) {
        logger.error("Unable to save csv file with telemetry events", ioe);
        return false;
    }

    return true;
}

From source file:com.roamtouch.menuserver.utils.FileUtils.java

public void storeLog(String text) {
    boolean first = false;
    File logFolder = new File(app.getSDCARD() + "/httpd/log/files/");
    if (!logFolder.exists()) {
        logFolder.mkdir();/*  w ww.j  av  a 2  s.  c o  m*/
    }
    String dateFormat = app.getTimeDate("dd_MM_yyyy");
    File logFile = new File(logFolder.toString() + "/" + getWeekDay() + "_" + dateFormat + "" + ".json");
    if (!logFile.exists()) {

        try {
            logFile.createNewFile();
            writeHTMLLog();
            first = true;
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {

        removeLastCharacter(logFile);
    }

    try {
        BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
        String[] data = text.split("-");
        String dataJson = toLogJSON(data);
        String d = null;
        if (first) {
            d = "[" + dataJson + "]";
        } else {
            d = "," + dataJson + "]";
        }
        String formatted = new String(d.getBytes("ISO-8859-1"), "UTF-8");
        buf.append(d);
        buf.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.jflyfox.modules.filemanager.FileManager.java

public void log(String filename, String msg) {
    try {//  ww  w  . jav a  2 s  . c  om
        BufferedWriter out = new BufferedWriter(new FileWriter(filename, true));
        out.append(msg + "\r\n");
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.roamtouch.menuserver.utils.FileUtils.java

public void storeBackupLog(String text) {
    boolean first = false;
    File logFolder = new File(app.getSDCARD() + "/httpd/backup/log");
    if (!logFolder.exists()) {
        logFolder.mkdir();/*w w  w .  j  a  v  a2s . co  m*/
    }
    String dateFormat = app.getTimeDate("dd_MM_yyyy");
    //File logFile = new File(logFolder.toString()+ "/" + getWeekDay() + "_" + dateFormat + "" + ".json");
    File logFile = new File(logFolder + "/backup_log.json");
    if (!logFile.exists()) {

        try {
            logFile.createNewFile();
            //writeHTMLLog();
            first = true;
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {

        removeLastCharacter(logFile);
    }

    try {
        BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
        String[] data = text.split("\\^");
        String dataJson = toBuckupLogJSON(data);
        String d = null;
        if (first) {
            d = "[" + dataJson + "]";
        } else {
            d = "," + dataJson + "]";
        }
        String formatted = new String(d.getBytes("ISO-8859-1"), "UTF-8");
        buf.append(d);
        buf.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

/**
 * Save new check./* w w w . j ava  2s  . c o m*/
 *
 * @param table the table
 * @param newChk the new chk
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void saveNewCheck(TABLE table, String newChk) throws IOException {
    if (!dataFolder.exists()) {
        dataFolder.mkdirs();
    }
    File file = new File(dataFolder, table.name() + ".dat");
    BufferedWriter bw = getWriter(file.getAbsolutePath());
    bw.append(newChk);
    bw.append("\r\n");
    bw.close();
    bw = null;
}