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:gov.nih.nci.ncicb.tcga.dcc.qclive.common.logging.FileLoggerDestination.java

protected void log(final String message) throws LoggerException {
    try {/*w  w  w .  j a  v a 2  s . c  om*/
        if (this.writer == null) {
            //noinspection IOResourceOpenedButNotSafelyClosed
            this.writer = new PrintWriter(new BufferedWriter(new FileWriter(filename, append)));
        }
        writer.append(message);
        writer.flush();
    } catch (IOException ioe) {
        throw new LoggerException(ioe);
    } finally {
        IOUtils.closeQuietly(writer);
        this.writer = null;
    }
}

From source file:com.android.internal.http.multipart.MultipartTest.java

public void testParts() throws Exception {
    StringBuffer filebuffer = new StringBuffer();
    String filepartStr = "this is file part";
    filebuffer.append(filepartStr);//from  w w  w.j a  va 2 s. co  m
    File upload = File.createTempFile("Multipart", "test");

    FileWriter outFile = new FileWriter(upload);
    BufferedWriter out = new BufferedWriter(outFile);
    try {
        out.write(filebuffer.toString());
        out.flush();
    } finally {
        out.close();
    }

    Part[] parts = new Part[3];
    parts[0] = new StringPart("stringpart", "PART1!!");
    parts[1] = new FilePart(upload.getName(), upload);
    parts[2] = new StringPart("stringpart", "PART2!!");

    MultipartEntity me = new MultipartEntity(parts);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    me.writeTo(os);
    Header h = me.getContentType();
    String boundry = EncodingUtils.getAsciiString(me.getMultipartBoundary());
    StringBuffer contentType = new StringBuffer("multipart/form-data");
    contentType.append("; boundary=");
    contentType.append(boundry);
    assertEquals("Multipart content type error", contentType.toString(), h.getValue());
    final String CRLF = "\r\n";
    StringBuffer output = new StringBuffer();

    output.append("--");
    output.append(boundry);
    output.append(CRLF);

    output.append("Content-Disposition: form-data; name=\"stringpart\"");
    output.append(CRLF);
    output.append("Content-Type: text/plain; charset=US-ASCII");
    output.append(CRLF);
    output.append("Content-Transfer-Encoding: 8bit");
    output.append(CRLF);
    output.append(CRLF);
    output.append("PART1!!");
    output.append(CRLF);

    output.append("--");
    output.append(boundry);
    output.append(CRLF);

    output.append("Content-Disposition: form-data; name=\"");
    output.append(upload.getName());
    output.append("\"; filename=\"");
    output.append(upload.getName());
    output.append("\"");

    output.append(CRLF);
    output.append("Content-Type: application/octet-stream; charset=ISO-8859-1");
    output.append(CRLF);
    output.append("Content-Transfer-Encoding: binary");
    output.append(CRLF);
    output.append(CRLF);
    output.append(filepartStr);
    output.append(CRLF);

    output.append("--");
    output.append(boundry);
    output.append(CRLF);

    output.append("Content-Disposition: form-data; name=\"stringpart\"");
    output.append(CRLF);
    output.append("Content-Type: text/plain; charset=US-ASCII");
    output.append(CRLF);
    output.append("Content-Transfer-Encoding: 8bit");
    output.append(CRLF);
    output.append(CRLF);
    output.append("PART2!!");
    output.append(CRLF);

    output.append("--");
    output.append(boundry);
    output.append("--");
    output.append(CRLF);
    // System.out.print(output.toString());
    assertEquals("Multipart content error", output.toString(), os.toString());

    // System.out.print(os.toString());
}

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   ww  w. ja va2 s.  c o  m
        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:es.ua.dlsi.patch.translation.LocalApertiumTranslator.java

public Set<String> getTranslation(final String input) {

    Set<String> output = new HashSet<>();
    String finalline = "";
    // pull from the map if already there

    try {/*from   w  ww .ja  v  a 2 s. c om*/
        String[] command = { "apertium", "-u", langCmd };
        ProcessBuilder probuilder = new ProcessBuilder(command);

        Process process = probuilder.start();
        OutputStream stdin = process.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
        writer.write(input);
        writer.newLine();
        writer.flush();
        writer.close();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            finalline += line;
        }
        br.close();

    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.exit(-1);
    }
    output.add(finalline);
    return output;
}

From source file:brugerautorisation.server.BrugerProtocol.java

private void cmd(List<String> msg) {
    OutputStreamWriter out = null;
    Writer writer = null;/*from  w w w  .ja v  a  2 s .co  m*/
    try {
        out = new OutputStreamWriter(server.getOutputStream());
        writer = new BufferedWriter(out);
        switch (msg.get(0).toLowerCase().replace("\n", "")) {
        case ("hello"):
            break;
        case ("login"):
            System.out.println("v");
            JSONObject json = new JSONObject(msg.get(1));
            JSONObject json_return = new JSONObject();
            try {
                Bruger b = ba.hentBruger(json.getString("username"), json.getString("password"));
                json_return.put("username", b.brugernavn);
            } catch (SOAPFaultException e) {
                json_return.put("error", e.getMessage());
            }
            writer.write(json_return.toString());
            writer.flush();
            //out.flush();
            break;
        case ("forgot_pass"):
            break;
        default:
            System.out.println("ikke fundet");
            break;
        }
    } catch (IOException ex) {
        Logger.getLogger(BrugerProtocol.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(BrugerProtocol.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            writer.close();
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(BrugerProtocol.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:files.FileUtils.java

public static boolean WriteFile(String pathFileText, String fileContent) {
    try {//  w w w .ja v a  2s. c o m
        File file = new File(pathFileText);

        //if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        //Collecting Data
        if (!CommonUtils.IsNullOrEmpty(fileContent)) {
            //true = append file
            FileWriter fileWritter = new FileWriter(file.getPath(), false);
            try (BufferedWriter bufferWritter = new BufferedWriter(fileWritter)) {
                bufferWritter.write(fileContent);
            }
            return true;
        }
    } catch (IOException ex) {
        return false;
    }
    return false;
}

From source file:com.textocat.textokit.commons.io.IoUtils.java

public static BufferedWriter openBufferedWriter(File file, String encoding, boolean append) throws IOException {
    FileOutputStream fos = openOutputStream(file, append);
    OutputStreamWriter osr;//  w w w. j  av a2  s. c  o m
    try {
        osr = new OutputStreamWriter(fos, encoding);
    } catch (UnsupportedEncodingException e) {
        closeQuietly(fos);
        throw e;
    }
    return new BufferedWriter(osr);
}

From source file:common.Utilities.java

public static boolean writeStringToFile(String filename, String stringToWrite) {
    try {//from  w  w  w  . j av a  2  s . c o  m
        FileWriter writer = new FileWriter(new File(filename));
        BufferedWriter bw = new BufferedWriter(writer);
        bw.write(stringToWrite);
        bw.flush();
        bw.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.zht.common.codegen.excute.impl.AbstractGenerator.java

/**
 * /*from  ww w  .j a v  a2  s .  co m*/
 */
public void generate(String templateFileName, Map<?, ?> data, String fileName) {
    try {
        String templateFileDir = templateFileName.substring(0, templateFileName.lastIndexOf("/"));
        String templateFile = templateFileName.substring(templateFileName.lastIndexOf("/") + 1,
                templateFileName.length());

        String genFileDir = fileName.substring(0, fileName.lastIndexOf("/"));
        Template template = GenConfigurationHelper.getConfiguration(templateFileDir).getTemplate(templateFile);
        template.setEncoding("UTF-8");
        org.apache.commons.io.FileUtils.forceMkdir(new File(genFileDir));
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"));
        // File output = new File(fileName);
        //Writer writer = new FileWriter(output);
        template.process(data, writer);
        writer.close();
    } catch (TemplateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:hsa.awp.common.dao.template.TemplateFileSystemDao.java

@Override
public void saveTemplate(String content, TemplateDetail templateDetail) {

    try {/* w  ww  . j a va 2  s. c  om*/
        File file = new File(generatePath(templateDetail));
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write(content);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}