Example usage for java.io FileWriter FileWriter

List of usage examples for java.io FileWriter FileWriter

Introduction

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

Prototype

public FileWriter(FileDescriptor fd) 

Source Link

Document

Constructs a FileWriter given a file descriptor, using the platform's java.nio.charset.Charset#defaultCharset() default charset .

Usage

From source file:emailworkshop.EmailWorkshop.java

public static void exe(ArrayList<Checkin> lista, String emailAutentica, String senhaAutentica,
        String emailRecebe, boolean enviaEmailParticipante) {
    if (emailAutentica.isEmpty() || senhaAutentica.isEmpty()) {
        System.exit(0);//from w  ww .j  av  a2  s .  com
    }
    FileWriter fw = null;
    try {
        fw = new FileWriter("relatorioDeEnvio.txt");
    } catch (IOException ex) {
        Logger.getLogger(EmailWorkshop.class.getName()).log(Level.SEVERE, null, ex);
    }
    int numCert = 2217;
    for (Checkin c : lista) {
        //if ("https://drive.google.com/open?id=0B0LxgGB17-B3aGVNMThsTXpWV0E".equals(c.getQrCode())) {
        gerarPDF(c.getNome(), numCert);
        try {
            if (!emailRecebe.isEmpty()) {
                enviaEmailComAnexo(emailAutentica, senhaAutentica, emailRecebe, c.getNome());
                System.out.println("certificado de " + c.getNome() + " gerado!");

                try {

                    fw.write("certificado de " + c.getNome() + " gerado!\n");

                } catch (IOException ex) {
                    Logger.getLogger(EmailWorkshop.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            if (enviaEmailParticipante) {
                System.out.println("envia email para " + c.getNome());
                enviaEmailComAnexo(emailAutentica, senhaAutentica, c.getEmail(), c.getNome());
            }
            //avisoDeEnvio(c.getNome());
        } catch (EmailException ex) {
            Logger.getLogger(EmailWorkshop.class.getName()).log(Level.SEVERE, null, ex);
        }

        //}
        numCert = numCert + 1;
    }
    try {
        fw.close();
    } catch (IOException ex) {
        Logger.getLogger(EmailWorkshop.class.getName()).log(Level.SEVERE, null, 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\"");
    }//from w w  w.j a  va2 s .co  m

    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:Main.java

/**
 * Dump a <code>String</code> to a text file.
 *
 * @param file The output file/*from   w w w .j  ava 2 s  . c  om*/
 * @param string The string to be dumped
 * @param encoding The encoding for the output file or null for default platform encoding
 * @exception IOException IO Error
        
 */
public static void serializeString(File file, String string, String encoding) throws IOException {
    final Writer fw = (encoding == null) ? new FileWriter(file)
            : new OutputStreamWriter(new FileOutputStream(file), encoding);
    try {
        fw.write(string);
        fw.flush();
    } finally {
        fw.close();
    }
}

From source file:hu.juranyi.zsolt.jauthortagger.util.TestUtils.java

public static File createEmptyFile(String fn) {
    File outFile = new File(TEST_DIR, fn);
    FileWriter w = null;//from ww  w.  j a  v  a 2s .  c  o m
    try {
        File parent = outFile.getParentFile();
        if (null != parent && !parent.exists()) {
            parent.mkdirs();
        }
        w = new FileWriter(outFile);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (null != w) {
            try {
                w.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return outFile;
}

From source file:Main.java

/**
 * Saves an index (Hashtable) to a file.
 * /*from w w  w .j a  v  a  2s . c o  m*/
 * @param root_
 *            The file where the index is stored in.
 * @param index
 *            The indextable.
 * @exception IOException
 *                If an internal error prevents the file from being written.
 */
public static void saveIndex(File root_, String name, Hashtable index) throws IOException {
    File indexfile = new File(root_, name);
    PrintWriter out = new PrintWriter(new FileWriter(indexfile));
    Enumeration keys = index.keys();
    String key = null;
    while (keys.hasMoreElements()) {
        key = (String) keys.nextElement();
        out.println(key);
        out.println((Long) index.get(key));
    }
    out.close();
}

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);// w  ww.j  a va 2s  .  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:fr.cnrs.sharp.reasoning.Harmonization.java

public static File harmonizeProv(File inputProv) throws IOException {
    Model inputGraph = FileManager.get().loadModel(inputProv.getAbsolutePath());
    Model harmonizedProv = harmonizeProv(inputGraph);

    Path pathInfProv = Files.createTempFile("PROV-inf-tgd-egd-", ".ttl");
    harmonizedProv.write(new FileWriter(pathInfProv.toFile()), "TTL");
    logger.info("PROV inferences file written to " + pathInfProv.toString());
    return pathInfProv.toFile();
}

From source file:Main.java

public static FileWriter getFileWriter(String filePath) {

    File xmlFile = new File(filePath);
    FileWriter writer = null;/*www. jav a  2s.c  om*/
    try {
        writer = new FileWriter(xmlFile);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return writer;
}

From source file:gov.nih.nci.caintegrator.application.query.GenomicDataFileWriter.java

/**
 * Writes a GenomicDataQueryResult to the given file.
 * @param result genomic query result to write in csv format.
 * @param csvFile to write file to.//from  w w  w.  ja  va2s . c  o m
 * @return csv file.
 */
public static File writeAsCsv(GenomicDataQueryResult result, File csvFile) {
    try {
        FileWriter writer = new FileWriter(csvFile);
        if (ResultsOrientationEnum.SUBJECTS_AS_COLUMNS.equals(result.getQuery().getOrientation())) {
            writeStandardOrientation(result, writer);
        } else {
            writeSubjectsAsRowsOrientation(result, writer);
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new IllegalArgumentException("Couldn't write file at the path " + csvFile.getAbsolutePath(), e);
    }
    return csvFile;
}

From source file:actors.ConfigUtil.java

/**
 * Generate the config file in the 'wherehows.app_folder' folder
 * The file name is {whEtlExecId}.config
 *
 * @param whEtlExecId//  w w w .  j  av  a  2s .  c o  m
 * @param props
 * @return void
 */
static void generateProperties(long whEtlExecId, Properties props, String outDir) throws IOException {
    File dir = new File(outDir);
    if (!dir.exists()) {
        dir.mkdirs();
    }

    File configFile = new File(dir, whEtlExecId + ".properties");
    FileWriter writer = new FileWriter(configFile);
    props.store(writer, "exec id : " + whEtlExecId + " job configurations");
    writer.close();
}