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:com.jgaap.backend.CLI.java

/**
 * Parses the arguments passed to jgaap from the command line. Will either
 * display the help or run jgaap on an experiment.
 * /* www  . java  2  s .c  om*/
 * @param args
 *            command line arguments
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption('h')) {
        String command = cmd.getOptionValue('h');
        if (command == null) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.setLeftPadding(5);
            helpFormatter.setWidth(100);
            helpFormatter.printHelp(
                    "jgaap -c [canon canon ...] -es [event] -ec [culler culler ...] -a [analysis] <-d [distance]> -l [file] <-s [file]>",
                    "Welcome to JGAAP the Java Graphical Authorship Attribution Program.\nMore information can be found at http://jgaap.com",
                    options, "Copyright 2013 Evaluating Variation in Language Lab, Duquesne University");
        } else {
            List<Displayable> list = new ArrayList<Displayable>();
            if (command.equalsIgnoreCase("c")) {
                list.addAll(Canonicizers.getCanonicizers());
            } else if (command.equalsIgnoreCase("es")) {
                list.addAll(EventDrivers.getEventDrivers());
            } else if (command.equalsIgnoreCase("ec")) {
                list.addAll(EventCullers.getEventCullers());
            } else if (command.equalsIgnoreCase("a")) {
                list.addAll(AnalysisDrivers.getAnalysisDrivers());
            } else if (command.equalsIgnoreCase("d")) {
                list.addAll(DistanceFunctions.getDistanceFunctions());
            } else if (command.equalsIgnoreCase("lang")) {
                list.addAll(Languages.getLanguages());
            }
            for (Displayable display : list) {
                if (display.showInGUI())
                    System.out.println(display.displayName() + " - " + display.tooltipText());
            }
            if (list.isEmpty()) {
                System.out.println("Option " + command + " was not found.");
                System.out.println("Please use c, es, d, a, or lang");
            }
        }
    } else if (cmd.hasOption('v')) {
        System.out.println("Java Graphical Authorship Attribution Program version 5.2.0");
    } else if (cmd.hasOption("ee")) {
        String eeFile = cmd.getOptionValue("ee");
        String lang = cmd.getOptionValue("lang");
        ExperimentEngine.runExperiment(eeFile, lang);
        System.exit(0);
    } else {
        JGAAP.commandline = true;
        API api = API.getPrivateInstance();
        String documentsFilePath = cmd.getOptionValue('l');
        if (documentsFilePath == null) {
            throw new Exception("No Documents CSV specified");
        }
        List<Document> documents;
        if (documentsFilePath.startsWith(JGAAPConstants.JGAAP_RESOURCE_PACKAGE)) {
            documents = Utils.getDocumentsFromCSV(
                    CSVIO.readCSV(com.jgaap.JGAAP.class.getResourceAsStream(documentsFilePath)));
        } else {
            documents = Utils.getDocumentsFromCSV(CSVIO.readCSV(documentsFilePath));
        }
        for (Document document : documents) {
            api.addDocument(document);
        }
        String language = cmd.getOptionValue("lang", "english");
        api.setLanguage(language);
        String[] canonicizers = cmd.getOptionValues('c');
        if (canonicizers != null) {
            for (String canonicizer : canonicizers) {
                api.addCanonicizer(canonicizer);
            }
        }
        String[] events = cmd.getOptionValues("es");
        if (events == null) {
            throw new Exception("No EventDriver specified");
        }
        for (String event : events) {
            api.addEventDriver(event);
        }
        String[] eventCullers = cmd.getOptionValues("ec");
        if (eventCullers != null) {
            for (String eventCuller : eventCullers) {
                api.addEventCuller(eventCuller);
            }
        }
        String analysis = cmd.getOptionValue('a');
        if (analysis == null) {
            throw new Exception("No AnalysisDriver specified");
        }
        AnalysisDriver analysisDriver = api.addAnalysisDriver(analysis);
        String distanceFunction = cmd.getOptionValue('d');
        if (distanceFunction != null) {
            api.addDistanceFunction(distanceFunction, analysisDriver);
        }
        api.execute();
        List<Document> unknowns = api.getUnknownDocuments();
        OutputStreamWriter outputStreamWriter;
        String saveFile = cmd.getOptionValue('s');
        if (saveFile == null) {
            outputStreamWriter = new OutputStreamWriter(System.out);
        } else {
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(saveFile));
        }
        Writer writer = new BufferedWriter(outputStreamWriter);
        for (Document unknown : unknowns) {
            writer.append(unknown.getFormattedResult(analysisDriver));
        }
        writer.append('\n');
    }
}

From source file:Main.java

/**
 * Write data row.//from  ww  w  .j a v a  2s  . c o  m
 * 
 * @param data the data
 * @param outputPath the output path
 */
public static void writeDataRow(String data, String outputPath) {
    File file = new File(outputPath);
    try {
        file.createNewFile();
    } catch (IOException e1) {
        e1.printStackTrace();
        System.exit(0);
    }
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.write(data);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(0);
    }
}

From source file:Main.java

/**
 * Write to file in given folder/*from   ww w  .j  a va 2 s. c o m*/
 * @param fcontent
 * @return
 */
public static boolean writeFile(String fcontent, String path) {

    /*
     * Write file contents to file path
     */
    try {
        File file = new File(path);
        // If file does not exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(fcontent);
        bw.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:Main.java

/**
 * Write data column.//from   www. ja v  a2  s  .  c o m
 * 
 * @param data the data
 * @param outputPath the output path
 */
public static void writeDataColumn(List<? extends Number> data, String outputPath) {
    File file = new File(outputPath);
    try {
        file.createNewFile();
    } catch (IOException e1) {
        e1.printStackTrace();
        System.exit(0);
    }
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        for (Number value : data) {
            writer.write(value.toString() + "\n");
        }
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(0);
    }
}

From source file:Main.java

/**
 * This method get string and create local file with that string
 * @param st//from www . j  a  va 2 s  .c o m
 * @param fileName
 */
private static void writeFile(String st, String fileName) {
    FileOutputStream fos = null;
    PrintWriter pw = null;

    try {
        File rootDir = new File("/storage/emulated/0/dbSuperZol/");

        fos = new FileOutputStream(new File(rootDir, fileName));
        pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fos)));

        pw.println(st);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (pw != null) {
            pw.close();
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

From source file:Main.java

public static void saveBoardToExternal(Context context, String fileName, JSONObject jsonObject) {
    File file = new File(getDirectoryBoards(), fileName);
    if (file.exists()) {
        file.delete();//  w  w w . jav a 2  s  .  c  o m
    }

    try {
        file.createNewFile();
        BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
        buf.append(jsonObject.toString());
        buf.close();
        addTomMediaScanner(context, file);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:edu.usc.qspr.Main.java

/**
 * The main method.//from ww w  .  j  av a2 s  .  c o  m
 *
 * @param args the arguments
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    double result;
    long start = System.currentTimeMillis();
    //TODO: to be commented
    //      args = new String("-i sample_inputs/5-1-3.qasm -f sample_inputs/fabric.ql -o output -p baseline -s 21 -v").split(" ");
    //      args = new String("-i ../sample_inputs/5-1-3.qasm -f ../sample_inputs/fabric.ql -p mvfb -s 2 -v").split(" ");

    parseInputs(args);

    if (RuntimeConfig.OUTPUT_TO_FILE) {
        outputFile = new PrintWriter(new BufferedWriter(new FileWriter(outputFileAddr, false)), true);
    } else { //writing to stdout
        outputFile = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true);
    }

    //Prints the current working directory
    if (RuntimeConfig.DEBUG)
        System.out.println("Current directory: " + System.getProperty("user.dir"));

    layout = LayoutParser.LayoutParser(fabricFileAddr);

    qasm = QASMParser.QASMParser(qasmFileAddr);

    eds = new EventDrivenSimulator(layout, qasm.getCommandsList(), outputFile);

    if (placementMethod.compareTo("center") == 0) {
        result = center();
    } else if (placementMethod.compareTo("baseline") == 0) {
        result = baseLine();
    } else if (placementMethod.compareTo("mc") == 0) {
        result = mc(m, false);
    } else { //default is mvfb
        result = mvfb(m);
    }
    outputFile.println("------------------------------------");
    outputFile.println("Execution latency: " + result + " us");
    long end = System.currentTimeMillis();
    outputFile.println("QSPR runtime " + (end - start) + " ms");

    if (RuntimeConfig.OUTPUT_TO_FILE) {
        outputFile.close();
    } else {
        outputFile.flush();
    }

    if (RuntimeConfig.VERBOSE) {
        System.out.println("Done.");
    }
}

From source file:Main.java

public static void writeLog(String log) {
    File file = new File("/sdcard/xh.log");
    if (!file.exists()) {
        try {//from  ww  w.j a  v a2s.  c  om
            file.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //            e.printStackTrace();
        }
    }
    BufferedWriter out = null;
    try {
        // Create file 
        FileWriter fstream = new FileWriter("/sdcard/xh.log", true);
        out = new BufferedWriter(fstream);
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss   ");
        String time = sdf.format(new Date(System.currentTimeMillis()));
        out.append(time);
        out.append(log);
        out.append("\r\n\r\n");
    } catch (Exception e) {//Catch exception if any
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
        }
    }
}

From source file:Main.java

/**
 * Converts a plain text file into TE3-input file
 *
 * @param plainfile/*from  www  .j a v  a  2 s  . c  o m*/
 * @return
 */
public static String Plain2TE3(String plainfile) {
    String outputfile = null;
    try {
        String line;
        boolean textfound = false;
        String header = "";
        String footer = "";
        String text = "";

        //process header (and dct)/text/footer
        outputfile = plainfile + ".TE3input";
        BufferedWriter te3writer = new BufferedWriter(new FileWriter(new File(outputfile)));
        BufferedReader inputReader = new BufferedReader(new FileReader(new File(plainfile)));

        try {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dctvalue = sdf.format(new Date());

            te3writer.write("<?xml version=\"1.0\" ?>");
            te3writer.write(
                    "\n<TimeML xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://timeml.org/timeMLdocs/TimeML_1.2.1.xsd\">\n");
            te3writer.write("\n<DOCID>" + (new File(plainfile)).getName() + "</DOCID>\n");
            te3writer.write("\n<DCT><TIMEX3 tid=\"t0\" type=\"DATE\" value=\"" + dctvalue
                    + "\" temporalFunction=\"false\" functionInDocument=\"CREATION_TIME\">" + dctvalue
                    + "</TIMEX3></DCT>\n");

            // read out text
            while ((line = inputReader.readLine()) != null) {
                text += line + "\n";
            }

            te3writer.write("\n<TEXT>\n" + text + "</TEXT>\n");
            te3writer.write("</TimeML>\n");

        } finally {
            if (inputReader != null) {
                inputReader.close();
            }
            if (te3writer != null) {
                te3writer.close();
            }
        }
    } catch (Exception e) {
        System.err.println("Errors found (TML_file_utils):\n\t" + e.toString() + "\n");
        if (System.getProperty("DEBUG") != null && System.getProperty("DEBUG").equalsIgnoreCase("true")) {
            e.printStackTrace(System.err);
        }
        return null;
    }
    return outputfile;
}

From source file:Main.java

/**
 * @param node/*from w  w w .j  a v  a 2  s .c  o  m*/
 * @throws IOException
 */
public static void serializeNode(Node node) throws IOException {
    if (writer == null)
        writer = new BufferedWriter(new OutputStreamWriter(System.out));

    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE:
        Document doc = (Document) node;
        writer.write("<?xml version=\"");
        writer.write(doc.getXmlVersion());
        writer.write("\" encoding=\"UTF-8\" standalone=\"");
        if (doc.getXmlStandalone())
            writer.write("yes");
        else
            writer.write("no");
        writer.write("\"?>\n");

        NodeList nodes = node.getChildNodes();
        if (nodes != null)
            for (int i = 0; i < nodes.getLength(); i++)
                serializeNode(nodes.item(i));
        break;
    case Node.ELEMENT_NODE:
        String name = node.getNodeName();
        writer.write("<" + name);
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node current = attributes.item(i);
            writer.write(" " + current.getNodeName() + "=\"");
            print(current.getNodeValue());
            writer.write("\"");
        }
        writer.write(">");

        NodeList children = node.getChildNodes();
        if (children != null) {
            //if ((children.item(0) != null) && (children.item(0).getNodeType() == Node.ELEMENT_NODE))
            //  writer.write("\n");

            for (int i = 0; i < children.getLength(); i++)
                serializeNode(children.item(i));
            if ((children.item(0) != null)
                    && (children.item(children.getLength() - 1).getNodeType() == Node.ELEMENT_NODE))
                writer.write("");
        }

        writer.write("</" + name + ">");
        break;
    case Node.TEXT_NODE:
        print(node.getNodeValue());
        break;
    case Node.CDATA_SECTION_NODE:
        writer.write("CDATA");
        print(node.getNodeValue());
        writer.write("");
        break;
    case Node.COMMENT_NODE:
        writer.write("<!-- " + node.getNodeValue() + " -->\n");
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        writer.write("<?" + node.getNodeName() + " " + node.getNodeValue() + "?>\n");
        break;
    case Node.ENTITY_REFERENCE_NODE:
        writer.write("&" + node.getNodeName() + ";");
        break;
    case Node.DOCUMENT_TYPE_NODE:
        DocumentType docType = (DocumentType) node;
        String publicId = docType.getPublicId();
        String systemId = docType.getSystemId();
        String internalSubset = docType.getInternalSubset();
        writer.write("<!DOCTYPE " + docType.getName());
        if (publicId != null)
            writer.write(" PUBLIC \"" + publicId + "\" ");
        else
            writer.write(" SYSTEM ");
        writer.write("\"" + systemId + "\"");
        if (internalSubset != null)
            writer.write(" [" + internalSubset + "]");
        writer.write(">\n");
        break;
    }
    writer.flush();
}