Example usage for java.io BufferedWriter BufferedWriter

List of usage examples for java.io BufferedWriter BufferedWriter

Introduction

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

Prototype

public BufferedWriter(Writer out) 

Source Link

Document

Creates a buffered character-output stream that uses a default-sized output buffer.

Usage

From source file:Main.java

public static void xmlToFile(Document doc, String fileNameToWrite) throws Exception {
    DOMSource domSource = new DOMSource(doc);
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileNameToWrite)));
    StreamResult streamResult = new StreamResult(out);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, streamResult);
}

From source file:Main.java

public static void saveUtfFileWithBOM(File file, String content) throws IOException {
    BufferedWriter bw = null;//from   w w w .j a  v  a2s .  c  o  m
    OutputStreamWriter osw = null;

    FileOutputStream fos = new FileOutputStream(file);
    try {
        // write UTF8 BOM mark if file is empty
        if (file.length() < 1) {
            final byte[] bom = new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
            fos.write(bom);
        }

        osw = new OutputStreamWriter(fos, "UTF-8");
        bw = new BufferedWriter(osw);
        if (content != null) {
            bw.write(content);
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        try {
            bw.close();
            fos.close();
        } catch (Exception ex) {
        }
    }
}

From source file:com.hp.test.framework.Reporting.removerunlinks.java

public static void removelinksforpreRuns(String FilePath, String FileName, int lastrun)
        throws FileNotFoundException, IOException {

    log.info("Removing hyper link for the last run");
    ArrayList<String> Links_To_Remove = new ArrayList<String>();

    for (int i = 1; i < lastrun; i++) {
        Links_To_Remove.add("href=\"Run_" + i + "\\CurrentRun.html\"");
    }//  ww w. j a  v a 2  s. com

    File source = new File(FilePath + FileName);
    File temp_file = new File(FilePath + "temp.html");
    BufferedReader in = new BufferedReader(new FileReader(source));
    BufferedWriter out = new BufferedWriter(new FileWriter(temp_file));
    String str = "";
    while ((str = in.readLine()) != null) {

        String temp_ar[] = str.split(" ");

        for (int i = 0; i < temp_ar.length; i++) {
            String temp = temp_ar[i].trim();
            if (!temp.equals("")) {

                if (Links_To_Remove.contains(temp)) {
                    out.write(" ");
                    out.newLine();

                } else {
                    out.write(temp);
                    out.newLine();

                }

            }
        }
    }

    out.close();
    in.close();
    out = null;
    in = null;

    source.delete();
    temp_file.renameTo(source);

}

From source file:apps.quantification.LearnQuantificationSVMPerf.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = LearnQuantificationSVMPerf.class.getName()
            + " [OPTIONS] <path to svm_perf_learn> <path to svm_perf_classify> <trainingIndexDirectory> <outputDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("f");
    OptionBuilder.withDescription("Number of folds");
    OptionBuilder.withLongOpt("f");
    OptionBuilder.isRequired(true);/*from   ww w.j a va2  s  . c  o m*/
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("c");
    OptionBuilder.withDescription("The c value for svm_perf (default 0.01)");
    OptionBuilder.withLongOpt("c");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("l");
    OptionBuilder.withDescription("The loss function to optimize (default 2):\n"
            + "               0  Zero/one loss: 1 if vector of predictions contains error, 0 otherwise.\n"
            + "               1  F1: 100 minus the F1-score in percent.\n"
            + "               2  Errorrate: Percentage of errors in prediction vector.\n"
            + "               3  Prec/Rec Breakeven: 100 minus PRBEP in percent.\n"
            + "               4  Prec@p: 100 minus precision at p in percent.\n"
            + "               5  Rec@p: 100 minus recall at p in percent.\n"
            + "               10  ROCArea: Percentage of swapped pos/neg pairs (i.e. 100 - ROCArea).");
    OptionBuilder.withLongOpt("l");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("w");
    OptionBuilder.withDescription("Choice of structural learning algorithm (default 9):\n"
            + "               0: n-slack algorithm described in [2]\n"
            + "               1: n-slack algorithm with shrinking heuristic\n"
            + "               2: 1-slack algorithm (primal) described in [5]\n"
            + "               3: 1-slack algorithm (dual) described in [5]\n"
            + "               4: 1-slack algorithm (dual) with constraint cache [5]\n"
            + "               9: custom algorithm in svm_struct_learn_custom.c");
    OptionBuilder.withLongOpt("w");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("p");
    OptionBuilder.withDescription("The value of p used by the prec@p and rec@p loss functions (default 0)");
    OptionBuilder.withLongOpt("p");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmPerfLearnerCustomizer classificationLearnerCustomizer = null;
    SvmPerfClassifierCustomizer classificationCustomizer = null;

    int folds = -1;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]);
        classificationCustomizer = new SvmPerfClassifierCustomizer(remainingArgs[1]);

        folds = Integer.parseInt(line.getOptionValue("f"));

        if (line.hasOption("c"))
            classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c")));

        if (line.hasOption("w"))
            classificationLearnerCustomizer.setW(Integer.parseInt(line.getOptionValue("w")));

        if (line.hasOption("p"))
            classificationLearnerCustomizer.setP(Integer.parseInt(line.getOptionValue("p")));

        if (line.hasOption("l"))
            classificationLearnerCustomizer.setL(Integer.parseInt(line.getOptionValue("l")));

        if (line.hasOption("v"))
            classificationLearnerCustomizer.printSvmPerfOutput(true);

        if (line.hasOption("s"))
            classificationLearnerCustomizer.setDeleteTrainingFiles(false);

        if (line.hasOption("t")) {
            classificationLearnerCustomizer.setTempPath(line.getOptionValue("t"));
            classificationCustomizer.setTempPath(line.getOptionValue("t"));
        }

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    assert (classificationLearnerCustomizer != null);

    if (remainingArgs.length != 4) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[2];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    String outputPath = remainingArgs[3];

    SvmPerfLearner classificationLearner = new SvmPerfLearner();

    classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer);

    FileSystemStorageManager fssm = new FileSystemStorageManager(indexPath, false);
    fssm.open();

    IIndex training = TroveReadWriteHelper.readIndex(fssm, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);

    final TextualProgressBar progressBar = new TextualProgressBar("Learning the quantifiers");

    IOperationStatusListener status = new IOperationStatusListener() {

        @Override
        public void operationStatus(double percentage) {
            progressBar.signal((int) percentage);
        }
    };

    QuantificationLearner quantificationLearner = new QuantificationLearner(folds, classificationLearner,
            classificationLearnerCustomizer, classificationCustomizer, ClassificationMode.PER_CATEGORY,
            new LogisticFunction(), status);

    IQuantifier[] quantifiers = quantificationLearner.learn(training);

    File executableFile = new File(classificationLearnerCustomizer.getSvmPerfLearnPath());
    IDataManager classifierDataManager = new SvmPerfDataManager(new SvmPerfClassifierCustomizer(
            executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_perf_classify"));
    String description = "_SVMPerf_C-" + classificationLearnerCustomizer.getC() + "_W-"
            + classificationLearnerCustomizer.getW() + "_L-" + classificationLearnerCustomizer.getL();
    if (classificationLearnerCustomizer.getL() == 4 || classificationLearnerCustomizer.getL() == 5)
        description += "_P-" + classificationLearnerCustomizer.getP();
    if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0)
        description += "_" + classificationLearnerCustomizer.getAdditionalParameters();
    String quantifierPrefix = indexName + "_Quantifier-" + folds + description;

    FileSystemStorageManager fssmo = new FileSystemStorageManager(
            outputPath + File.separatorChar + quantifierPrefix, true);
    fssmo.open();
    QuantificationLearner.write(quantifiers, fssmo, classifierDataManager);
    fssmo.close();

    BufferedWriter bfs = new BufferedWriter(
            new FileWriter(outputPath + File.separatorChar + quantifierPrefix + "_rates.txt"));
    TShortDoubleHashMap simpleTPRs = quantificationLearner.getSimpleTPRs();
    TShortDoubleHashMap simpleFPRs = quantificationLearner.getSimpleFPRs();
    TShortDoubleHashMap scaledTPRs = quantificationLearner.getScaledTPRs();
    TShortDoubleHashMap scaledFPRs = quantificationLearner.getScaledFPRs();

    ContingencyTableSet contingencyTableSet = quantificationLearner.getContingencyTableSet();

    short[] cats = simpleTPRs.keys();
    for (int i = 0; i < cats.length; ++i) {
        short cat = cats[i];
        String catName = training.getCategoryDB().getCategoryName(cat);
        ContingencyTable contingencyTable = contingencyTableSet.getCategoryContingencyTable(cat);
        double simpleTPR = simpleTPRs.get(cat);
        double simpleFPR = simpleFPRs.get(cat);
        double scaledTPR = scaledTPRs.get(cat);
        double scaledFPR = scaledFPRs.get(cat);
        String line = quantifierPrefix + "\ttrain\tsimple\t" + catName + "\t" + cat + "\t"
                + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t"
                + contingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n";
        bfs.write(line);
        line = quantifierPrefix + "\ttrain\tscaled\t" + catName + "\t" + cat + "\t" + contingencyTable.tp()
                + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn()
                + "\t" + scaledTPR + "\t" + scaledFPR + "\n";
        bfs.write(line);
    }
    bfs.close();
}

From source file:Main.java

/**
 * Save {@link String} to {@link File} witht the specified encoding
 *
 * @param string {@link String}/*from   ww  w  . j a  v a2s  .  c om*/
 * @param path   Path of the file
 * @param string Encoding
 * @throws IOException
 */
public static void saveStringToFile(String string, File path, String encoding) throws IOException {
    if (path.exists()) {
        path.delete();
    }

    if ((path.getParentFile().mkdirs() || path.getParentFile().exists())
            && (path.exists() || path.createNewFile())) {
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), encoding));
        writer.write(string);
        writer.close();
    }
}

From source file:Main.java

public static String UpdateScore(String userName, int br) {

    String retStr = "";

    try {//from ww w  .ja  v a  2 s  .  c o m
        URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/AzurirajHighScore.php");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        Log.e("http", "por1");

        JSONObject data = new JSONObject();

        data.put("username", userName);
        data.put("broj", br);

        Log.e("http", "por3");

        Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString());
        String query = builder.build().getEncodedQuery();

        Log.e("http", "por4");

        OutputStream os = conn.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        bw.write(query);
        Log.e("http", "por5");
        bw.flush();
        bw.close();
        os.close();
        int responseCode = conn.getResponseCode();

        Log.e("http", String.valueOf(responseCode));
        if (responseCode == HttpURLConnection.HTTP_OK) {
            retStr = inputStreamToString(conn.getInputStream());
        } else
            retStr = String.valueOf("Error: " + responseCode);

        Log.e("http", retStr);

    } catch (Exception e) {
        Log.e("http", "greska");
    }
    return retStr;
}

From source file:Main.java

public static String UdatePlayerBT(String userName, String device) {

    String retStr = "";

    try {/* www  .j a  v a  2s. c o m*/
        URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/PostaviBTdevice.php");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        Log.e("http", "por1");

        JSONObject data = new JSONObject();

        data.put("username", userName);
        data.put("bt_device", device);

        Log.e("http", "por3");

        Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString());
        String query = builder.build().getEncodedQuery();

        Log.e("http", "por4");

        OutputStream os = conn.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        bw.write(query);
        Log.e("http", "por5");
        bw.flush();
        bw.close();
        os.close();
        int responseCode = conn.getResponseCode();

        Log.e("http", String.valueOf(responseCode));
        if (responseCode == HttpURLConnection.HTTP_OK) {
            retStr = inputStreamToString(conn.getInputStream());
        } else
            retStr = String.valueOf("Error: " + responseCode);

        Log.e("http", retStr);

    } catch (Exception e) {
        Log.e("http", "greska");
    }
    return retStr;
}

From source file:csv.FileManager.java

static public boolean appendItems(String fileName, ArrayList<ArrayList<String>> data,
        boolean firstRowIsHeader) {
    try {//  ww w. ja  v a 2 s . c  o m
        BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
        CSVWriter writer = new CSVWriter(out);
        String[] t = new String[0];
        for (ArrayList<String> row : data) {
            if (!firstRowIsHeader) {
                boolean found = false;
                for (String str : row) {
                    if (!str.isEmpty()) {
                        found = true;
                    }
                }
                if (found)
                    writer.writeNext(row.toArray(t));
            } else
                firstRowIsHeader = false;
        }
        out.close();
        return true;
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return false;
    }
}

From source file:apps.ParsedPost.java

public static void main(String args[]) {

    Options options = new Options();

    options.addOption(INPUT_PARAM, null, true, INPUT_DESC);
    options.addOption(OUTPUT_PARAM, null, true, OUTPUT_DESC);
    options.addOption(MAX_NUM_REC_PARAM, null, true, MAX_NUM_REC_DESC);
    options.addOption(DEBUG_PRINT_PARAM, null, false, DEBUG_PRINT_DESC);
    options.addOption(EXCLUDE_CODE_PARAM, null, false, EXCLUDE_CODE_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    HashMap<String, ParsedPost> hQuestions = new HashMap<String, ParsedPost>();

    try {//from   ww w  .  ja va  2  s  .  co m
        CommandLine cmd = parser.parse(options, args);

        String inputFile = cmd.getOptionValue(INPUT_PARAM);

        if (null == inputFile)
            Usage("Specify: " + INPUT_PARAM, options);

        String outputFile = cmd.getOptionValue(OUTPUT_PARAM);

        if (null == outputFile)
            Usage("Specify: " + OUTPUT_PARAM, options);

        InputStream input = CompressUtils.createInputStream(inputFile);
        BufferedWriter output = new BufferedWriter(new FileWriter(new File(outputFile)));

        int maxNumRec = Integer.MAX_VALUE;

        String tmp = cmd.getOptionValue(MAX_NUM_REC_PARAM);

        if (tmp != null)
            maxNumRec = Integer.parseInt(tmp);

        boolean debug = cmd.hasOption(DEBUG_PRINT_PARAM);

        boolean excludeCode = cmd.hasOption(EXCLUDE_CODE_PARAM);

        System.out.println("Processing at most " + maxNumRec + " records, excluding code? " + excludeCode);

        XmlIterator xi = new XmlIterator(input, ROOT_POST_TAG);

        String elem;

        output.write("<?xml version='1.0' encoding='UTF-8'?><ystfeed>\n");

        for (int num = 1; num <= maxNumRec && !(elem = xi.readNext()).isEmpty(); ++num) {
            ParsedPost post = null;
            try {
                post = parsePost(elem, excludeCode);

                if (!post.mAcceptedAnswerId.isEmpty()) {
                    hQuestions.put(post.mId, post);
                } else if (post.mpostIdType.equals("2")) {
                    String parentId = post.mParentId;
                    String id = post.mId;
                    if (!parentId.isEmpty()) {
                        ParsedPost parentPost = hQuestions.get(parentId);
                        if (parentPost != null && parentPost.mAcceptedAnswerId.equals(id)) {
                            output.write(createYahooAnswersQuestion(parentPost, post));
                            hQuestions.remove(parentId);
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Error parsing record # " + num + ", error message: " + e);
            }
            if (debug) {
                System.out.println(String.format("%s parentId=%s acceptedAnswerId=%s type=%s", post.mId,
                        post.mParentId, post.mAcceptedAnswerId, post.mpostIdType));
                System.out.println("================================");
                if (!post.mTitle.isEmpty()) {
                    System.out.println(post.mTitle);
                    System.out.println("--------------------------------");
                }
                System.out.println(post.mBody);
                System.out.println("================================");
            }
        }

        output.write("</ystfeed>\n");

        input.close();
        output.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:dao.EntryDaoTest.java

@BeforeClass
public static void setUpClass() {
    String fSeparator = File.separator;
    try {//from ww  w.j  ava  2  s .  co  m
        File folder = new File(
                System.getProperty("user.dir") + fSeparator + "MyDiaryBook" + fSeparator + "Users" + fSeparator
                        + "Panagiwtis Georgiadis" + fSeparator + "Entries" + fSeparator + "Texnologia2");
        folder.mkdirs();

        File textFolder = new File(folder.toString() + fSeparator + "Texts");
        textFolder.mkdirs();
        File textFile = new File(textFolder.toString() + fSeparator + "test.txt");
        BufferedWriter bw;
        FileWriter fw;
        fw = new FileWriter(textFile, true);
        bw = new BufferedWriter(fw);
        bw.write("test0123456789");
        if (bw != null)
            bw.close();
        fw.close();
        File imageFolder = new File(folder.toString() + fSeparator + "Images");
        imageFolder.mkdirs();
        String imageSourcePath = System.getProperty("user.dir") + fSeparator + "src" + fSeparator + "test"
                + fSeparator + "java" + fSeparator + "resources" + fSeparator + "testImg.jpg";
        File imageSourceFile = new File(imageSourcePath);
        FileUtils.copyFileToDirectory(imageSourceFile, imageFolder);

        String videoSourcePath = System.getProperty("user.dir") + fSeparator + "src" + fSeparator + "test"
                + fSeparator + "java" + fSeparator + "resources" + fSeparator + "testVideo.mp4";
        File videoSourceFile = new File(videoSourcePath);
        File videoFolder = new File(folder.toString() + fSeparator + "Videos");
        videoFolder.mkdirs();
        FileUtils.copyFileToDirectory(videoSourceFile, videoFolder);
    } catch (IOException ex) {
        Logger.getLogger(EntryDaoTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}