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:com.shazam.chimprunner.ResultsStorage.java

public void storeResults(Map<TestCaseEvent, Double> results) throws ResultStorageException {
    FileWriter writer = null;//www.  j a v  a2  s  . c  o  m
    CSVWriter csvWriter = null;
    try {
        writer = new FileWriter(new File(output, TIMINGS_FILE));
        csvWriter = new CSVWriter(writer);
        write(results, csvWriter);
    } catch (IOException e) {
        throw new ResultStorageException("Failed to write results", e);
    } finally {
        closeQuietly(csvWriter);
        closeQuietly(writer);
    }
}

From source file:mrdshinse.md2html.util.FileUtil.java

/**
 * Create file by String./*from w w  w  .  ja  v  a2 s .  c  o  m*/
 *
 * @param file File class for output file.
 * @param str file content
 * @return Processed file
 */
public static File create(File file, String str) {

    try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)))) {
        pw.print(str);
    } catch (IOException ex) {
        LOG.error(ex);
        return file;
    }
    return file;
}

From source file:org.neo4j.ogm.auth.AuthenticationTest.java

@BeforeClass
public static void setUp() throws Exception {

    Path authStore = Files.createTempFile("neo4j", "credentials");
    authStore.toFile().deleteOnExit();/* w  w  w . j  a va 2s .c o m*/
    try (Writer authStoreWriter = new FileWriter(authStore.toFile())) {
        IOUtils.write(
                "neo4j:SHA-256,03C9C54BF6EEF1FF3DFEB75403401AA0EBA97860CAC187D6452A1FCF4C63353A,819BDB957119F8DFFF65604C92980A91:",
                authStoreWriter);
    }

    neoPort = TestUtils.getAvailablePort();

    try {
        ServerControls controls = TestServerBuilders.newInProcessBuilder()
                .withConfig("dbms.security.auth_enabled", "true")
                .withConfig("org.neo4j.server.webserver.port", String.valueOf(neoPort))
                .withConfig("dbms.security.auth_store.location", authStore.toAbsolutePath().toString())
                .newServer();

        initialise(controls);

    } catch (Exception e) {
        throw new RuntimeException("Error starting in-process server", e);
    }
}

From source file:main.InitConfig.java

void create() throws FileNotFoundException, UnsupportedEncodingException, IOException {
    JSONObject obj = new JSONObject();
    obj.put("Port", 8080);

    try (FileWriter fw = new FileWriter(Config.ROOT_PATH + "/config/JettyES.json")) {
        fw.write(obj.toString(4));/*from w w  w . ja  va 2  s. co m*/
        fw.write("\n");
        fw.flush();
        fw.close();
    }

    JSONObject objDB = new JSONObject();
    objDB.put("Database_Driver", "org.postgresql.Driver");
    objDB.put("Database_URL", "jdbc:postgresql://localhost:5432/test_db");
    objDB.put("Database_User_Name", "postgres");
    objDB.put("Database_Password", "a");

    JSONObject objDBRoot = new JSONObject();
    objDBRoot.put("Company", objDB);
    objDBRoot.put("Sub", objDB);

    try (FileWriter fw = new FileWriter(Config.ROOT_PATH + "/config/Database.json")) {
        fw.write(objDBRoot.toString(4));
        fw.write("\n");
        fw.flush();
        fw.close();
    }
}

From source file:ca.uvic.cs.tagsea.wizards.TagNetworkSender.java

public static synchronized void send(String xml, IProgressMonitor sendMonitor, int id)
        throws InvocationTargetException {
    sendMonitor.beginTask("Uploading Tags", 100);
    sendMonitor.subTask("Saving Temporary file...");
    File location = TagSEAPlugin.getDefault().getStateLocation().toFile();
    File temp = new File(location, "tagsea.temp.file.txt");
    if (temp.exists()) {
        String message = "Unable to send tags. Unable to create temporary file.";
        IOException ex = new IOException(message);
        throw (new InvocationTargetException(ex, message));
    }//from w  w  w .j a  v  a  2 s .  c o  m
    try {
        FileWriter writer = new FileWriter(temp);
        writer.write(xml);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }
    sendMonitor.worked(5);
    sendMonitor.subTask("Uploading Tags...");
    String uploadScript = "http://stgild.cs.uvic.ca/cgi-bin/tagSEAUpload.cgi";
    PostMethod post = new PostMethod(uploadScript);

    String fileName = getToday() + ".txt";
    try {
        Part[] parts = { new StringPart("KIND", "tag"), new FilePart("MYLAR" + id, fileName, temp) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        HttpClient client = new HttpClient();
        int status = client.executeMethod(post);
        String resp = getData(post.getResponseBodyAsStream());
        if (status != 200) {
            IOException ex = new IOException(resp);
            throw (ex);
        }
    } catch (IOException e) {
        throw new InvocationTargetException(e, e.getLocalizedMessage());
    } finally {
        sendMonitor.worked(90);
        sendMonitor.subTask("Deleting Temporary File");
        temp.delete();
        sendMonitor.done();
    }

}

From source file:au.org.emii.geoserver.extensions.filters.layer.data.io.FilterConfigurationFile.java

public void write(List<Filter> filters) throws TemplateException, IOException {
    FilterConfigurationWriter configurationWriter = new FilterConfigurationWriter(filters);

    Writer writer = null;//w ww.jav  a 2  s  .  com
    try {
        writer = new FileWriter(getFilePath());
        configurationWriter.write(writer);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:com.hp.test.framework.htmparse.GenerateFailReport.java

public static void genarateFailureReport(File SourceFile, String TargetPath) {

    try {/* w  w  w. j  av a 2  s  .c  o m*/

        Map<String, Map<String, List<String>>> Suites_list = new HashMap<>();

        for (String key : UpdateTestCaseDesciption.TestCaseDesMap.keySet()) {
            Map<String, List<String>> test_status_list = new HashMap<>();
            String status = UpdateTestCaseDesciption.TestcaseStatusMap.get(key);

            String[] temp_ar = key.split("\\\\");

            List<String> Des = new ArrayList<String>();
            Des.add(UpdateTestCaseDesciption.TestCaseDesMap.get(key));
            Des.add(status);
            test_status_list.put(key, Des);
            if (!Suites_list.containsKey(temp_ar[0])) {
                Suites_list.put(temp_ar[0], test_status_list);
            } else {
                Map<String, List<String>> temp_status_list = Suites_list.get(temp_ar[0]);
                temp_status_list.put(key, Des);
                Suites_list.put(temp_ar[0], temp_status_list);
            }

        }

        String[] filename = SourceFile.getName().split("/.");
        BufferedReader in = new BufferedReader(new FileReader(SourceFile));
        BufferedWriter out = new BufferedWriter(new FileWriter(TargetPath + "\\" + filename[0]));

        String str;

        while ((str = in.readLine()) != null) {

            if (str.contains("All Suites")) {
                out.write(str);
                for (String key : Suites_list.keySet()) {

                    String Filter = "<option class=\"filterOption\"" + " value=\"" + key + "\">" + key
                            + "</option>";
                    out.write(Filter);
                    out.write("\n");

                }
                continue;
            }

            if (str.contains("#suiteFilter")) {
                out.write(str);
                for (String key : Suites_list.keySet()) {

                    String suiteFilter = "if($(this).val()=='" + key + "'){      $('.all').hide();$('." + key
                            + "').show(); }";
                    out.write(suiteFilter);
                    out.write("\n");

                }
                continue;
            }

            out.write(str);
        }

        in.close();

        int i = 1;

        for (String key : Suites_list.keySet()) {
            Map<String, List<String>> temp_status_list = Suites_list.get(key);
            for (String TestCase : temp_status_list.keySet()) {

                List<String> temp_list = temp_status_list.get(TestCase);
                // String[] temp_ar=temp.split("^");
                String status = temp_list.get(1);
                String classTag = status + " all " + key;

                out.write("<tr class=\"" + classTag + "\">");
                out.write("\n");
                out.write("<td>" + String.valueOf(i) + "</td>");
                out.write("\n");
                out.write("\n");
                out.write("<td>" + key + "</td>");

                out.write("\n");
                out.write("<td><font color=\"#013ADF\" size=\"3\">" + temp_list.get(0) + "</font></td>");
                out.write("\n");

                if (status.contains("fail")) {
                    out.write(
                            "<td  style=\"font-weight:bold;vertical-align:middle;white-space:nowrap;font size=\"35;\"\"><font size=\"3\" color=\"Red\">"
                                    + "Fail" + "</font></td>");
                }
                if (status.contains("pass")) {
                    out.write(
                            "<td  style=\"font-weight:bold;vertical-align:middle;white-space:nowrap;font size=\"35;\"\"><font color=\"Green\">"
                                    + "Pass" + "</font></td>");
                }
                if (status.contains("skip")) {
                    out.write(
                            "<td  style=\"font-weight:bold;vertical-align:middle;white-space:nowrap;font size=\"35;\"\"><font color=\"Blue\">"
                                    + "Skip" + "</font></td>");
                }
                out.write("\n");
                out.write("</tr>");
                out.write("\n");
                i = i + 1;

            }
        }

        out.write("</Table>");
        out.write("</body>");
        out.write("</html>");
        out.close();
        System.out.println("Genarating Failure Report is Completed ");

    } catch (IOException e) {
        System.out.println("Exception in Replacing Counts in .js file is done " + e.getMessage());
    }

}

From source file:com.shazam.fork.io.HtmlGenerator.java

public void generateHtml(String htmlTemplateResource, File output, String filename, Object... htmlModels) {
    FileWriter writer = null;//from  ww w .  j  av a  2 s  .c  o  m
    try {
        Mustache mustache = mustacheFactory.compile(htmlTemplateResource);
        File indexFile = new File(output, filename);
        writer = new FileWriter(indexFile);
        mustache.execute(writer, htmlModels);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        closeQuietly(writer);
    }
}

From source file:main.java.RMDupper.java

public static void main(String[] args) throws IOException {
    System.err.println("DeDup v" + VERSION);
    // the command line parameters
    Options helpOptions = new Options();
    helpOptions.addOption("h", "help", false, "show this help page");
    Options options = new Options();
    options.addOption("h", "help", false, "show this help page");
    options.addOption("i", "input", true,
            "the input file if this option is not specified,\nthe input is expected to be piped in");
    options.addOption("o", "output", true, "the output folder. Has to be specified if input is set.");
    options.addOption("m", "merged", false,
            "the input only contains merged reads.\n If this option is specified read names are not examined for prefixes.\n Both the start and end of the aligment are considered for all reads.");
    options.addOption("v", "version", false, "the version of DeDup.");
    HelpFormatter helpformatter = new HelpFormatter();
    CommandLineParser parser = new BasicParser();
    try {/*from w w  w . j  av  a 2 s  . c om*/
        CommandLine cmd = parser.parse(helpOptions, args);
        if (cmd.hasOption('h')) {
            helpformatter.printHelp(CLASS_NAME, options);
            System.exit(0);
        }
    } catch (ParseException e1) {
    }

    String input = "";
    String outputpath = "";
    Boolean merged = Boolean.FALSE;
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('i')) {
            input = cmd.getOptionValue('i');
            piped = false;
        }
        if (cmd.hasOption('o')) {
            outputpath = cmd.getOptionValue('o');
        }
        if (cmd.hasOption('m')) {
            merged = Boolean.TRUE;
        }
        if (cmd.hasOption('v')) {
            System.out.println("DeDup v" + VERSION);
            System.exit(0);
        }
    } catch (ParseException e) {
        helpformatter.printHelp(CLASS_NAME, options);
        System.err.println(e.getMessage());
        System.exit(0);
    }
    DecimalFormat df = new DecimalFormat("##.##");

    if (piped) {
        RMDupper rmdup = new RMDupper(System.in, System.out, merged);
        rmdup.readSAMFile();

        System.err.println("We are in piping mode!");
        System.err.println("Total reads: " + rmdup.dupStats.total + "\n");
        System.err.println("Reverse removed: " + rmdup.dupStats.removed_reverse + "\n");
        System.err.println("Forward removed: " + rmdup.dupStats.removed_forward + "\n");
        System.err.println("Merged removed: " + rmdup.dupStats.removed_merged + "\n");
        System.err.println("Total removed: " + (rmdup.dupStats.removed_forward + rmdup.dupStats.removed_merged
                + rmdup.dupStats.removed_reverse) + "\n");
        if (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_forward
                + rmdup.dupStats.removed_reverse == 0) {
            System.err.println("Duplication Rate: " + df.format(0.00));
        } else {
            System.err.println("Duplication Rate: "
                    + df.format((double) (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse
                            + rmdup.dupStats.removed_forward) / (double) rmdup.dupStats.total));
        }

    } else {
        if (outputpath.length() == 0) {
            System.err.println("The output folder has to be specified");
            helpformatter.printHelp(CLASS_NAME, options);
            System.exit(0);
        }

        //Check whether we have a directory as output path, else produce error message and quit!

        File f = new File(outputpath);
        if (!f.isDirectory()) {
            System.err.println("The output folder should be a folder and not a file!");
            System.exit(0);
        }

        File inputFile = new File(input);
        File outputFile = new File(
                outputpath + "/" + Files.getNameWithoutExtension(inputFile.getAbsolutePath()) + "_rmdup.bam");
        File outputlog = new File(
                outputpath + "/" + Files.getNameWithoutExtension(inputFile.getAbsolutePath()) + ".log");
        File outputhist = new File(
                outputpath + "/" + Files.getNameWithoutExtension(inputFile.getAbsolutePath()) + ".hist");

        try {
            FileWriter fw = new FileWriter(outputlog);
            FileWriter histfw = new FileWriter(outputhist);
            BufferedWriter bfw = new BufferedWriter(fw);
            BufferedWriter histbfw = new BufferedWriter(histfw);

            RMDupper rmdup = new RMDupper(inputFile, outputFile, merged);
            rmdup.readSAMFile();
            rmdup.inputSam.close();
            rmdup.outputSam.close();

            bfw.write("Total reads: " + rmdup.dupStats.total + "\n");
            bfw.write("Reverse removed: " + rmdup.dupStats.removed_reverse + "\n");
            bfw.write("Forward removed: " + rmdup.dupStats.removed_forward + "\n");
            bfw.write("Merged removed: " + rmdup.dupStats.removed_merged + "\n");
            bfw.write("Total removed: " + (rmdup.dupStats.removed_forward + rmdup.dupStats.removed_merged
                    + rmdup.dupStats.removed_reverse) + "\n");
            bfw.write("Duplication Rate: "
                    + df.format((double) (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse
                            + rmdup.dupStats.removed_forward) / (double) rmdup.dupStats.total));
            bfw.flush();
            bfw.close();

            histbfw.write(rmdup.oc.getHistogram());
            histbfw.flush();
            histbfw.close();

            System.out.println("Total reads: " + rmdup.dupStats.total + "\n");
            System.out.println("Unmerged removed: "
                    + (rmdup.dupStats.removed_forward + rmdup.dupStats.removed_reverse) + "\n");
            System.out.println("Merged removed: " + rmdup.dupStats.removed_merged + "\n");
            System.out.println("Total removed: " + (rmdup.dupStats.removed_forward
                    + rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse) + "\n");
            if (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_forward
                    + rmdup.dupStats.removed_reverse == 0) {
                System.out.println("Duplication Rate: " + df.format(0.00));
            } else {
                System.out.println("Duplication Rate: "
                        + df.format((double) (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse
                                + rmdup.dupStats.removed_forward) / (double) rmdup.dupStats.total));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.pentacog.mctracker.SaveServerListTask.java

@Override
protected Void doInBackground(final ArrayList<Server>... params) {
    File serverFile = new File(context.getFilesDir(), MCServerTrackerActivity.SERVER_CACHE_FILE);
    try {// ww  w  .j av a  2  s .c o m
        if (!serverFile.exists()) {
            serverFile.createNewFile();
        }
        BufferedWriter bw = new BufferedWriter(new FileWriter(serverFile), 4000);

        JSONArray array = new JSONArray();
        for (Server server : params[0]) {
            array.put(server.toJSON());
        }

        bw.write(array.toString());
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    context = null;
    return null;
}