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.visva.voicerecorder.utils.Utils.java

public static boolean isCheckValidDurationTime() {
    String dataFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCallRecorder/data";
    File dataFile = new File(dataFilePath);
    String lastFileName = "";
    String line = null;//  ww  w . jav a 2  s . c  o m
    long durationTime = 0L;
    ArrayList<String> lines = new ArrayList<String>();
    String finalStringToWriteOut = "";
    try {
        BufferedReader br = new BufferedReader(new FileReader(dataFile));
        while ((line = br.readLine()) != null) {
            lastFileName = line.split(";")[0];
            lines.add(line);
        }
        br.close();
        for (int i = 0; i < lines.size() - 1; i++) {
            finalStringToWriteOut += lines.get(i) + "\n";
        }
        FileWriter fileWriter = new FileWriter(dataFile, false);
        BufferedWriter out = new BufferedWriter(fileWriter);
        out.append(finalStringToWriteOut);
        out.close();
        try {
            durationTime = getDuration(CheapSoundFile.create(lastFileName, null));
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
    } catch (IOException e) {

    }
    // The valid duration time is at least equal or more than 2 seconds for the length of a call.
    if (durationTime > 2000) {
        return true;
    } else {
        File mediaFile = new File(lastFileName);
        mediaFile.delete();
        MyCallRecorderApplication.getInstance().stopActivity();
        return false;
    }
}

From source file:org.scify.NewSumServer.Server.Utils.Main.java

private static boolean SplitterTrainingFileChanged() {
    boolean bChanged = false;
    String sStartsWith = "FileSize";
    String sLocalSep = "=";
    // get value of current size
    File fSentenceTrainer = new File(
            "./src/org/scify/NewSumServer/Server/Summarisation/SentenceSplitterTraining.txt");
    long lCurrentSize = fSentenceTrainer.length();
    // read file that has stored data about previous file size
    File fFileSize = new File(sToolPath + "FileSize.txt");
    if (fFileSize.exists()) {
        long lOldFileSize;
        // read file and get the file size from the previous run
        if (fFileSize.canRead()) {
            FileInputStream fstream;
            try {
                fstream = new FileInputStream(fFileSize);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                // Get the object of DataInputStream
                String sLine;//w w  w.j a va2 s .c o m
                while ((sLine = br.readLine()) != null) {
                    if (sLine.startsWith(sStartsWith)) {
                        // get value of previous file size
                        lOldFileSize = Long.valueOf(sLine.split("=")[1].trim());
                        // check if different values
                        bChanged = (lCurrentSize != lOldFileSize);
                        // overwrite data with new value
                        BufferedWriter bw = null;
                        bw = new BufferedWriter(new FileWriter(fFileSize, false));
                        // update data to file
                        bw.append(sStartsWith).append(sLocalSep);
                        bw.append(String.valueOf(lCurrentSize));
                        bw.close();
                    }
                }
                in.close();
            } catch (FileNotFoundException ex) {
                LOGGER.log(Level.SEVERE, "File Not Found (Exception): {0}", fFileSize.toString());
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, null, ex.getMessage());
            }

        } else {
            LOGGER.log(Level.SEVERE, "Error: Cannot read from file: {0}", fFileSize.toString());
        }
    } else {
        try {
            // create it for the first time
            fFileSize.createNewFile();
            BufferedWriter bw = null;
            bw = new BufferedWriter(new FileWriter(fFileSize, false));
            // write initial data to file
            bw.append(sStartsWith).append(sLocalSep);
            bw.append(String.valueOf(lCurrentSize));
            bw.close();
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, "Could not create file {0}", fFileSize.toString());
        }
    }
    return bChanged;
}

From source file:com.github.seqware.queryengine.system.exporters.JSONDumper.java

/**
 * <p>dumpVCFFromFeatureSetID.</p>
 *
 * @param fSet a {@link com.github.seqware.queryengine.model.FeatureSet} object.
 * @param file a {@link java.lang.String} object.
 *///  www .j  av a  2s . co  m
public static void dumpVCFFromFeatureSetID(FeatureSet fSet, String file) {
    BufferedWriter outputStream = null;

    try {
        if (file != null) {
            outputStream = new BufferedWriter(new FileWriter(file));
        } else {
            outputStream = new BufferedWriter(new OutputStreamWriter(System.out));
        }
    } catch (IOException e) {
        Logger.getLogger(JSONDumper.class.getName()).fatal("Exception thrown starting export to file:", e);
        System.exit(-1);
    }

    // fall-through if plugin-fails
    try {
        for (Feature feature : fSet) {
            StringBuilder buffer = new StringBuilder();
            boolean caught = outputFeatureInVCF(buffer, feature, fSet);
            outputStream.append(buffer);
            outputStream.newLine();
        }
        outputStream.flush();
    } catch (IOException e) {
        Logger.getLogger(JSONDumper.class.getName()).fatal("Exception thrown exporting to file:", e);
        System.exit(-1);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:org.vivoweb.harvester.util.FileAide.java

/**
 * Resolves the path and sets the contents of the file from a text string
 * @param path the path to resolve//from w  ww .j  a  v a 2s  . co m
 * @param value the value to set as the text content
 * @param overwrite overwrite an existing file
 * @throws IOException error resolving
 */
public static void setTextContent(String path, String value, boolean overwrite) throws IOException {
    if (path == null) {
        throw new IllegalArgumentException("File path must not be null");
    }
    BufferedWriter bw = null;
    try {
        if (!overwrite && exists(path)) {
            throw new IOException("Failed to set file text content because file " + path + " already exists.");
        }
        createFile(path);
        if (!isWriteable(path)) {
            throw new IOException("Insufficient file system privileges to modify file " + path);
        }
        bw = new BufferedWriter(new OutputStreamWriter(getOutputStream(path)));
        bw.append(value);
        bw.close();
    } catch (IOException e) {
        if (bw != null) {
            try {
                bw.close();
            } catch (Exception ignore) {
                // Ignore
            }
        }
        throw e;
    } finally {
        if (bw != null) {
            try {
                bw.close();
            } catch (Exception ignore) {
                // Ignore
            }
        }
    }
}

From source file:com.tencent.wetest.common.util.ReportUtil.java

@SuppressLint("SimpleDateFormat")
public static synchronized String saveReport() {

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

        path = WTApplication.getContext().getFilesDir().getPath();
        String versionName = ((WTApplication) WTApplication.getContext()).getApkinfo().getVersionName();

        packageName = ((WTApplication) WTApplication.getContext()).getApkinfo().getPackagename();
        appName = ((WTApplication) WTApplication.getContext()).getApkinfo().getAppname();
        ;
        datasource = ((WTApplication) WTApplication.getContext()).getReport();

        if (datasource != null)
            datas = datasource.getDatalist();

        size = datas.size();

        Date now = new Date();

        long timeStart = -1;
        long timeEnd = -1;
        boolean hasBaseTime = false;

        if (datasource.getBaseTime() == -1) {

            hasBaseTime = false;

            timeEnd = (new Date()).getTime();

            if (timeEnd == -1) {

                timeEnd = now.getTime();

                timeStart = (timeEnd - (SystemClock.uptimeMillis() - datasource.getBaseColock()))
                        + (datasource.getTimeStart() - datasource.getBaseColock());

            } else {

                timeStart = (timeEnd - (SystemClock.uptimeMillis() - datasource.getBaseColock()))
                        + (datasource.getTimeStart() - datasource.getBaseColock());

                ((WTApplication) WTApplication.getContext()).getReport().setBaseTime(timeEnd);
                ((WTApplication) WTApplication.getContext()).getReport()
                        .setBaseColock(SystemClock.uptimeMillis());

            }

        } else {

            hasBaseTime = true;

            timeStart = datasource.getBaseTime() + datasource.getTimeStart() - datasource.getBaseColock();

            timeEnd = datasource.getBaseTime() + SystemClock.uptimeMillis() - datasource.getBaseColock();

        }

        File f;
        File indexfile = new File(path + "/wtIndex");

        if (((WTApplication) WTApplication.getContext()).getCurrTestFile() == null) {

            name = "wt" + now.getTime();

            String fileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/wetest";
            ToolUtil.createDir(fileDir);

            f = new File(fileDir + "/" + name);
            ((WTApplication) WTApplication.getContext()).setCurrTestFile(f);

        } else {
            f = ((WTApplication) WTApplication.getContext()).getCurrTestFile();
            name = f.getName();

        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String isRoot = ((WTApplication) WTApplication.getContext()).isRoot() ? "1" : "0";

        String content_index = name + "/" + formatter.format(timeEnd) + "/" + appName.replaceFirst("\\s+", "")
                + "/" + packageName + "/" + (timeEnd - timeStart) / 1000 + "/" + timeStart + "/" + timeEnd + "/"
                + versionName + "/" + isRoot + "/" + "";

        ((WTApplication) WTApplication.getContext()).getTestReports().add(name);

        if (!f.exists()) {
            f.createNewFile();
        }

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

        JsonResult json_res = readFileReport(f);

        JSONObject cpu = new JSONObject();

        JSONObject natived = new JSONObject();
        JSONObject dalvik = new JSONObject();
        JSONObject total = new JSONObject();

        JSONObject networkIn = new JSONObject();
        JSONObject networkOut = new JSONObject();

        JSONObject fps = new JSONObject();

        JSONObject time = new JSONObject();

        JSONObject tag = new JSONObject();

        JSONObject temperature = new JSONObject();

        JSONObject current = new JSONObject();

        for (ReportData data : datas) {

            if (!hasBaseTime) {

                long gap = data.getTime() - datasource.getTimeStart();

                long offset = gap > 0 ? gap : 0;

                json_res.getContent_f_time().put((timeStart + offset) / 1000);

                //Logger.debug("dataTime is " + formatter.format(timeStart + offset));

            } else {

                json_res.getContent_f_time().put((data.getTime()) / 1000);

                //Logger.debug("dataTime is " + formatter.format(data.getTime()));

            }

            json_res.getContent_f_cpu().put(data.getCpu());

            json_res.getContent_f_native().put(data.getpNative());
            json_res.getContent_f_dalvik().put(data.getpDalvik());
            json_res.getContent_f_total().put(data.getpTotal());

            json_res.getContent_f_networkIn().put(data.getpNetworUsagekIn());
            json_res.getContent_f_networkOut().put(data.getpNetworUsagekOut());
            json_res.getContent_f_Fps().put(data.getFps());

            json_res.getContent_f_Tag().put(data.getTag());

            json_res.getContent_f_temperature().put(data.getpTemperature());

            json_res.getContent_f_current().put(data.getpCurrent());

        }

        cpu.put("cpu", json_res.getContent_f_cpu());

        natived.put("native", json_res.getContent_f_native());
        dalvik.put("dalvik", json_res.getContent_f_dalvik());
        total.put("total", json_res.getContent_f_total());

        networkIn.put("networkIn", json_res.getContent_f_networkIn());
        networkOut.put("networkOut", json_res.getContent_f_networkOut());
        time.put("time", json_res.getContent_f_time());

        fps.put("fps", json_res.getContent_f_Fps());
        tag.put("tag", json_res.getContent_f_Tag());

        temperature.put("temperature", json_res.getContent_f_temperature());
        current.put("current", json_res.getContent_f_current());

        BufferedWriter writer = new BufferedWriter(new FileWriter(f, false));

        writer.append(cpu.toString());
        writer.newLine();

        writer.append(natived.toString());
        writer.newLine();

        writer.append(dalvik.toString());
        writer.newLine();

        writer.append(total.toString());
        writer.newLine();

        writer.append(networkIn.toString());
        writer.newLine();

        writer.append(networkOut.toString());
        writer.newLine();

        writer.append(time.toString());
        writer.newLine();

        writer.append(fps.toString());
        writer.newLine();

        writer.append(tag.toString());

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

        updateRecord(indexfile, name, content_index);

    } catch (Exception e) {
        Logger.error("report save exception :" + e.toString());
        e.printStackTrace();
    }

    return name;

}

From source file:org.scify.NewSumServer.Server.Utils.Main.java

private static void writeConfigFile() {
    HashMap switches = new HashMap<String, String>();
    switches.put("BaseDir", sBaseDir);
    switches.put("PathToSources", sPathToSources);
    switches.put("indexPath", sindexPath);
    switches.put("SummaryPath", sSummaryPath);
    switches.put("ArticlePath", sArticlePath);
    switches.put("ToolPath", sToolPath);
    switches.put("sCatsDaysFile", sPathToCatsPerDaysFile);
    switches.put("useInputDirData", String.valueOf(bUseInputDirData));
    switches.put("ArticleMaxDays", String.valueOf(iArticleDays));
    switches.put("DebugRun", String.valueOf(bDebugRun));
    switches.put("NVSThreshold", String.valueOf(NVSThreshold));
    switches.put("SSThreshold", String.valueOf(SSThreshold));
    //        switches.put("SplitterTraining", String.valueOf(lFileSize));
    //write Config File, so that FreeService reads values from it
    File fConfig = new File(sBaseDir + "ServerConfig.txt");
    if (fConfig.exists()) {
        fConfig.delete();/*from ww  w.  jav a  2s  .c  o  m*/
    }
    try {
        fConfig.createNewFile();
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
    }
    if (fConfig.canWrite()) {
        try {
            BufferedWriter bw = null;
            bw = new BufferedWriter(new FileWriter(fConfig, true));
            Iterator Iter = switches.entrySet().iterator();
            while (Iter.hasNext()) {
                Map.Entry tmpS = (Map.Entry) Iter.next();
                bw.append((String) tmpS.getKey() + "=" + (String) tmpS.getValue());
                bw.append("\n");
            }
            bw.close();
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
        }
    } else {
        try {
            throw new IOException("Cannot write to file " + fConfig.getName());
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
}

From source file:com.netflix.lipstick.Main.java

public static boolean dryrun(String scriptFile, PigContext pigContext)
        throws RecognitionException, IOException {
    BufferedReader rd = new BufferedReader(new FileReader(scriptFile));

    DryRunGruntParser dryrun = new DryRunGruntParser(rd, scriptFile, pigContext);

    boolean hasMacro = dryrun.parseStopOnError();

    if (hasMacro) {
        String expandedFile = scriptFile.replace(".substituted", ".expanded");
        BufferedWriter fw = new BufferedWriter(new FileWriter(expandedFile));
        fw.append(dryrun.getResult());
        fw.close();//w ww  . ja v  a  2s  .  co m
    }
    return hasMacro;
}

From source file:edu.isi.pfindr.learn.util.PairsFileIO.java

public static void generatePairsFromStringAndFileContentWithNoClass(String userInput, String inputFilePath,
        String outputFilePath) {/*from   w ww .j  ava 2  s.  co m*/

    List<String> phenotypeList = new ArrayList<String>();

    try {
        phenotypeList = FileUtils.readLines(new File(inputFilePath));
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    String[] phenotype2;
    StringBuffer outputBuffer = new StringBuffer();

    BufferedWriter bw = null;
    try {
        bw = new BufferedWriter(new FileWriter(outputFilePath));
        for (int j = 0; j < phenotypeList.size(); j++) {
            phenotype2 = phenotypeList.get(j).split("\t");

            outputBuffer.append(String.format("%s\t%s\t%d\n", userInput, phenotype2[3], 0));
            bw.append(outputBuffer.toString());
            outputBuffer.setLength(0);
        }
    } catch (IOException io) {
        try {
            if (bw != null) {
                bw.close();
                bw = null;
            }
            io.printStackTrace();
        } catch (IOException e) {
            System.out.println("Problem occured while closing output stream  " + bw);
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bw != null) {
                bw.close();
                bw = null;
            }
        } catch (IOException e) {
            System.out.println("Problem occured while closing output stream  " + bw);
            e.printStackTrace();
        }
    }
}

From source file:org.gnucash.android.export.ExporterAsyncTask.java

/**
 * Copies a file from <code>src</code> to <code>dst</code>
 * @param src Absolute path to the source file
 * @param dst Absolute path to the destination file
 * @throws IOException if the file could not be copied
 *//*from  w  w w .ja v a  2  s.c om*/
private static List<String> splitQIF(File src, File dst) throws IOException {
    // split only at the last dot
    String[] pathParts = dst.getPath().split("(?=\\.[^\\.]+$)");
    ArrayList<String> splitFiles = new ArrayList<String>();
    String line;
    BufferedReader in = new BufferedReader(new FileReader(src));
    BufferedWriter out = null;
    try {
        while ((line = in.readLine()) != null) {
            if (line.startsWith(QifHelper.INTERNAL_CURRENCY_PREFIX)) {
                String currencyCode = line.substring(1);
                if (out != null) {
                    out.close();
                }
                String newFileName = pathParts[0] + "_" + currencyCode + pathParts[1];
                splitFiles.add(newFileName);
                out = new BufferedWriter(new FileWriter(newFileName));
            } else {
                if (out == null) {
                    throw new IllegalArgumentException(src.getPath() + " format is not correct");
                }
                out.append(line).append('\n');
            }
        }
    } finally {
        in.close();
        if (out != null) {
            out.close();
        }
    }
    return splitFiles;
}

From source file:canreg.client.analysis.Tools.java

/**
 *
 * @param popoutput/*  w w w . ja  va  2  s  .c  om*/
 * @param startYear
 * @param populations
 * @param separator
 * @throws IOException
 * @throws canreg.common.database.IncompatiblePopulationDataSetException
 */
public static void writePopulationsToFile(BufferedWriter popoutput, int startYear,
        PopulationDataset[] populations, String separator)
        throws IOException, IncompatiblePopulationDataSetException {
    String popheader = "YEAR" + separator;
    popheader += "AGE_GROUP_LABEL" + separator;
    popheader += "AGE_GROUP" + separator;
    popheader += "SEX" + separator;
    popheader += "COUNT" + separator;
    popheader += "REFERENCE_COUNT" + separator;
    popheader += "AGE_GROUP_SIZE";
    popoutput.append(popheader);
    popoutput.newLine();
    int thisYear = startYear;
    for (PopulationDataset popset : populations) {
        if (popset != null) {
            String[] ageGroupNames = popset.getAgeGroupStructure().getAgeGroupNames();
            for (PopulationDatasetsEntry pop : popset.getAgeGroups()) {
                popoutput.append(thisYear + "").append(separator);
                popoutput.append(ageGroupNames[pop.getAgeGroup()]).append(separator);
                popoutput.append(pop.getStringRepresentationOfAgeGroupsForFile(separator)).append(separator);
                // get reference pop
                popoutput.append(
                        popset.getReferencePopulationForAgeGroupIndex(pop.getSex(), pop.getAgeGroup()) + "")
                        .append(separator);
                popoutput
                        .append(popset.getAgeGroupStructure().getSizeOfAgeGroupByIndex(pop.getAgeGroup()) + "");
                popoutput.newLine();
            }
        }
        thisYear++;
    }
    popoutput.flush();
}