Example usage for java.io PrintWriter write

List of usage examples for java.io PrintWriter write

Introduction

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

Prototype

public void write(String s) 

Source Link

Document

Writes a string.

Usage

From source file:Main.java

public static void main(String[] args) {
    char c = 'a';

    PrintWriter pw = new PrintWriter(System.out);

    // write char
    pw.write(c);
    pw.write('b');

    // flush the writer
    pw.flush();//  w w  w  .j a  va  2s  . c  o m

}

From source file:Main.java

public static void main(String[] args) {
    try {/*from w  ww. j a v  a  2s.c  om*/
        char[] chars = new char[2];
        chars[0] = '\u4F60';
        chars[1] = '\u597D';
        String encoding = "GB18030";
        File textFile = new File("C:\\temp\\myFile.txt");
        PrintWriter writer = new PrintWriter(textFile, encoding);
        writer.write(chars);
        writer.close();

        // read back
        InputStreamReader reader = new InputStreamReader(new FileInputStream(textFile), encoding);
        char[] chars2 = new char[2];
        reader.read(chars2);
        System.out.print(chars2[0]);
        System.out.print(chars2[1]);
        reader.close();
    } catch (IOException e) {
        System.out.println(e.toString());
    }
}

From source file:Main.java

public static void main(String[] args) {
    String s = "Hello";
    try {/*from w  ww. j ava  2 s . c om*/

        PrintWriter pw = new PrintWriter(System.out);

        // write strings
        pw.write(s);
        pw.write(" World");

        // flush the writer
        pw.flush();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) {
    int i = 70;/* w ww  .  ja v  a2 s .co  m*/

    PrintWriter pw = new PrintWriter(System.out);

    // write integer as ASCII characters
    pw.write(i);
    pw.write(76);

    // flush the writer
    pw.flush();

}

From source file:base64test.Base64Test.java

/**
 * @param args the command line arguments
 *///ww w .  j a  v  a 2  s . co m
public static void main(String[] args) {
    try {
        if (!Base64.isBase64(args[0])) {
            throw new Exception("Arg 1 is not a Base64 string!");
        } else {
            String decodedBase64String = new String(Base64.decodeBase64(args[0]));
            File tempFile = File.createTempFile("base64Test", ".tmp");
            tempFile.deleteOnExit();
            FileWriter fw = new FileWriter(tempFile, false);
            PrintWriter pw = new PrintWriter(fw);
            pw.write(decodedBase64String);
            pw.close();
            String fileType = getFileType(tempFile.toPath());
            System.out.println(fileType);
            System.in.read();
        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

From source file:Main.java

public static void main(String[] args) {
    String s = "tutorial from java2s.com";
    try {/*w ww.  j  av  a 2  s  .c  o m*/

        // create a new stream at specified file
        PrintWriter pw = new PrintWriter(System.out);

        // write the string in the file
        pw.write(s);

        // flush the writer
        pw.flush();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    try {/*from   ww  w  .  j a va  2s.c  om*/
        char[] chars = new char[2];
        chars[0] = '\u4F60';
        chars[1] = '\u597D';
        String encoding = "GB18030";
        File textFile = new File("C:\\temp\\myFile.txt");
        PrintWriter writer = new PrintWriter(textFile,

                encoding);
        writer.write(chars);
        writer.close();

        // read back
        InputStreamReader reader = new InputStreamReader(new FileInputStream(textFile), encoding);
        char[] chars2 = new char[2];
        reader.read(chars2);
        System.out.print(chars2[0]);
        System.out.print(chars2[1]);
        reader.close();
    } catch (IOException e) {
        System.out.println(e.toString());
    }
}

From source file:eu.skqs.bertie.standalone.BertieStandalone.java

public static void main(String[] args) {

    // Options/*from   ww w . j  a v a2 s  . c  o m*/
    Option file = OptionBuilder.withArgName("file").withLongOpt("file").hasArg()
            .withDescription("File to annotate").create("f");

    Option directory = OptionBuilder.withArgName("directory").withLongOpt("directory").hasArg()
            .withDescription("Directory to annotate").create("d");

    Option owl = OptionBuilder.withArgName("owl").withLongOpt("owl").hasArg()
            .withDescription("OWL file to use in annotation").create("o");

    Option plain = OptionBuilder.withLongOpt("plain").withDescription("Plain text file format").create("p");

    Option tei = OptionBuilder.withLongOpt("tei").withDescription("TEI file format").create("t");

    Option mode = OptionBuilder.withArgName("extract|minimal|maximal|prosody").withLongOpt("mode").hasArg()
            .withDescription("Mode to operate in").create("m");

    Option clean = OptionBuilder.withArgName("T0,T1,T3").withLongOpt("clean").hasArg()
            .withDescription("Remove gives types, MUST START UPPERCASE").create("c");

    Options options = new Options();
    options.addOption(file);
    options.addOption(directory);
    options.addOption(owl);
    options.addOption(plain);
    options.addOption(tei);
    options.addOption(mode);
    options.addOption(clean);

    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmdline = null;

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    BertieStandalone standalone = new BertieStandalone();
    String documentPath = null;

    // Check for custom OWL
    if (cmdline.hasOption("owl")) {
        owlPath = cmdline.getOptionValue("owl");
    }

    // Check for clean
    if (cmdline.hasOption("clean")) {
        typesToRemove = cmdline.getOptionValue("clean");
    }

    // Check for mode
    if (cmdline.hasOption("mode")) {
        String currentMode = cmdline.getOptionValue("mode");

        if (currentMode.equals("extract")) {
            extractMode = true;
        } else if (currentMode.equals("poetry")) {
            poetryMode = true;
        }

        analysisMode = currentMode;
    }

    // Check for directory option
    if (cmdline.hasOption("directory")) {
        // We support TEI directorys only
        if (!cmdline.hasOption("tei")) {
            logger.log(Level.WARNING, "TEI file format must be selected with directory argument");
            System.exit(-1);
        }

        String directoryPath = cmdline.getOptionValue("directory");

        if (extractMode) {
            try {
                standalone.extractWithCollectionReader(directoryPath);
            } catch (Exception e) {
            }

            System.exit(0);
        }

        try {
            standalone.processWithCollectionReader(directoryPath);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }

        System.exit(0);
    }

    // Check for file option
    if (cmdline.hasOption("file")) {
        // TODO: clean this up
        documentPath = cmdline.getOptionValue("file");
        filePath = cmdline.getOptionValue("file");

        // TEI
        if (cmdline.hasOption("tei")) {
            try {
                processWithFile();
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(-1);
            }
            System.exit(0);
        }

        // Check for plain option
        if (!cmdline.hasOption("plain")) {
            logger.log(Level.WARNING, "Plain text format must be selected with file argument");
            System.exit(-1);
        }
    } else {
        logger.log(Level.WARNING, "No file argument given. Quitting.");
        formatter.printHelp("bertie", options);
        System.exit(-1);
    }

    // Make sure we have a document path
    if (documentPath == null) {
        logger.log(Level.WARNING, "Document path is empty. Quitting.");
        System.exit(-1);
    }

    // Read the document
    try {
        String encodingType = "UTF-8";

        BufferedReader fileReader = new BufferedReader(
                new InputStreamReader(new FileInputStream(documentPath), encodingType));

        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = fileReader.readLine()) != null) {
            sb.append(line + newLine);
        }

        String input = sb.toString();
        fileReader.close();

        String output = standalone.process(input);
        if (output == null) {
            logger.log(Level.WARNING, "Empty processing result.");
            System.exit(-1);
        }

        PrintWriter fileWriter = new PrintWriter(documentPath, encodingType);
        fileWriter.write(output);
        fileWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.citec.sc.matoll.process.Matoll_CreateMax.java

public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException,
        InstantiationException, IllegalAccessException, ClassNotFoundException, Exception {

    String directory;//from   www . j  av a2 s .c o m
    String gold_standard_lexicon;
    String output_lexicon;
    String configFile;
    Language language;
    String output;

    Stopwords stopwords = new Stopwords();

    HashMap<String, Double> maxima;
    maxima = new HashMap<String, Double>();

    if (args.length < 3) {
        System.out.print("Usage: Matoll --mode=train/test <DIRECTORY> <CONFIG>\n");
        return;

    }

    //      Classifier classifier;

    directory = args[1];
    configFile = args[2];

    final Config config = new Config();

    config.loadFromFile(configFile);

    gold_standard_lexicon = config.getGoldStandardLexicon();

    String model_file = config.getModel();

    output_lexicon = config.getOutputLexicon();
    output = config.getOutput();

    language = config.getLanguage();

    LexiconLoader loader = new LexiconLoader();
    Lexicon gold = loader.loadFromFile(gold_standard_lexicon);

    Set<String> uris = new HashSet<>();
    //        Map<Integer,String> sentence_list = new HashMap<>();
    Map<Integer, Set<Integer>> mapping_words_sentences = new HashMap<>();

    //consider only properties
    for (LexicalEntry entry : gold.getEntries()) {
        try {
            for (Sense sense : entry.getSenseBehaviours().keySet()) {
                String tmp_uri = sense.getReference().getURI().replace("http://dbpedia.org/ontology/", "");
                if (!Character.isUpperCase(tmp_uri.charAt(0))) {
                    uris.add(sense.getReference().getURI());
                }
            }
        } catch (Exception e) {
        }
        ;
    }

    ModelPreprocessor preprocessor = new ModelPreprocessor(language);
    preprocessor.setCoreferenceResolution(false);
    Set<String> dep = new HashSet<>();
    dep.add("prep");
    dep.add("appos");
    dep.add("nn");
    dep.add("dobj");
    dep.add("pobj");
    dep.add("num");
    preprocessor.setDEP(dep);

    List<File> list_files = new ArrayList<>();

    if (config.getFiles().isEmpty()) {
        File folder = new File(directory);
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.toString().contains(".ttl"))
                list_files.add(file);
        }
    } else {
        list_files.addAll(config.getFiles());
    }
    System.out.println(list_files.size());

    int sentence_counter = 0;
    Map<String, Set<Integer>> bag_words_uri = new HashMap<>();
    Map<String, Integer> mapping_word_id = new HashMap<>();
    for (File file : list_files) {
        Model model = RDFDataMgr.loadModel(file.toString());
        for (Model sentence : getSentences(model)) {
            String reference = getReference(sentence);
            reference = reference.replace("http://dbpedia/", "http://dbpedia.org/");
            if (uris.contains(reference)) {
                sentence_counter += 1;
                Set<Integer> words_ids = getBagOfWords(sentence, stopwords, mapping_word_id);
                //TODO: add sentence preprocessing
                String obj = getObject(sentence);
                String subj = getSubject(sentence);
                preprocessor.preprocess(sentence, subj, obj, language);
                //TODO: also return marker if object or subject of property (in SPARQL this has to be optional of course)
                String parsed_sentence = getParsedSentence(sentence);
                try (FileWriter fw = new FileWriter("mapping_sentences_to_ids_goldstandard.tsv", true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        PrintWriter out = new PrintWriter(bw)) {
                    out.println(sentence_counter + "\t" + parsed_sentence);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                for (Integer word_id : words_ids) {
                    if (mapping_words_sentences.containsKey(word_id)) {
                        Set<Integer> tmp_set = mapping_words_sentences.get(word_id);
                        tmp_set.add(sentence_counter);
                        mapping_words_sentences.put(word_id, tmp_set);

                    } else {
                        Set<Integer> tmp_set = new HashSet<>();
                        tmp_set.add(sentence_counter);
                        mapping_words_sentences.put(word_id, tmp_set);
                    }

                }
                if (bag_words_uri.containsKey(reference)) {
                    Set<Integer> tmp = bag_words_uri.get(reference);
                    for (Integer w : words_ids) {
                        tmp.add(w);

                    }
                    bag_words_uri.put(reference, tmp);
                } else {
                    Set<Integer> tmp = new HashSet<>();
                    for (Integer w : words_ids) {
                        tmp.add(w);
                    }
                    bag_words_uri.put(reference, tmp);
                }
            }

        }
        model.close();

    }

    PrintWriter writer = new PrintWriter("bag_of_words_only_goldstandard.tsv");
    StringBuilder string_builder = new StringBuilder();
    for (String r : bag_words_uri.keySet()) {
        string_builder.append(r);
        for (Integer i : bag_words_uri.get(r)) {
            string_builder.append("\t");
            string_builder.append(i);
        }
        string_builder.append("\n");
    }
    writer.write(string_builder.toString());
    writer.close();

    writer = new PrintWriter("mapping_words_to_sentenceids_goldstandard.tsv");
    string_builder = new StringBuilder();
    for (Integer w : mapping_words_sentences.keySet()) {
        string_builder.append(w);
        for (int i : mapping_words_sentences.get(w)) {
            string_builder.append("\t");
            string_builder.append(i);
        }
        string_builder.append("\n");
    }
    writer.write(string_builder.toString());
    writer.close();

}

From source file:com.galois.fiveui.HeadlessRunner.java

/**
 * @param args list of headless run description filenames
 * @throws IOException/*  ww  w .  jav a2 s  .c  om*/
 * @throws URISyntaxException
 * @throws ParseException
 */
@SuppressWarnings("static-access")
public static void main(final String[] args) throws IOException, URISyntaxException, ParseException {

    // Setup command line options
    Options options = new Options();
    Option help = new Option("h", "print this help message");
    Option output = OptionBuilder.withArgName("outfile").hasArg().withDescription("write output to file")
            .create("o");
    Option report = OptionBuilder.withArgName("report directory").hasArg()
            .withDescription("write HTML reports to given directory").create("r");
    options.addOption(output);
    options.addOption(report);
    options.addOption("v", false, "verbose output");
    options.addOption("vv", false, "VERY verbose output");
    options.addOption(help);

    // Parse command line options
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Command line option parsing failed.  Reason: " + e.getMessage());
        System.exit(1);
    }

    // Display help if requested
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("headless <input file 1> [<input file 2> ...]", options);
        System.exit(1);
    }

    // Set logging levels
    BasicConfigurator.configure();
    Logger fiveuiLogger = Logger.getLogger("com.galois.fiveui");
    Logger rootLogger = Logger.getRootLogger();
    if (cmd.hasOption("v")) {
        fiveuiLogger.setLevel(Level.DEBUG);
        rootLogger.setLevel(Level.ERROR);
    } else if (cmd.hasOption("vv")) {
        fiveuiLogger.setLevel(Level.DEBUG);
        rootLogger.setLevel(Level.DEBUG);
    } else {
        fiveuiLogger.setLevel(Level.ERROR);
        rootLogger.setLevel(Level.ERROR);
    }

    // Setup output file if requested
    PrintWriter outStream = null;
    if (cmd.hasOption("o")) {
        String outfile = cmd.getOptionValue("o");
        try {
            outStream = new PrintWriter(new BufferedWriter(new FileWriter(outfile)));
        } catch (IOException e) {
            System.err.println("Could not open outfile for writing: " + cmd.getOptionValue("outfile"));
            System.exit(1);
        }
    } else {
        outStream = new PrintWriter(new BufferedWriter(new PrintWriter(System.out)));
    }

    // Setup HTML reports directory before the major work happens in case we
    // have to throw an exception.
    PrintWriter summaryFile = null;
    PrintWriter byURLFile = null;
    PrintWriter byRuleFile = null;
    if (cmd.hasOption("r")) {
        String repDir = cmd.getOptionValue("r");
        try {
            File file = new File(repDir);
            if (!file.exists()) {
                file.mkdir();
                logger.info("report directory created: " + repDir);
            } else {
                logger.info("report directory already exists!");
            }
            summaryFile = new PrintWriter(new FileWriter(repDir + File.separator + "summary.html"));
            byURLFile = new PrintWriter(new FileWriter(repDir + File.separator + "byURL.html"));
            byRuleFile = new PrintWriter(new FileWriter(repDir + File.separator + "byRule.html"));
        } catch (IOException e) {
            System.err.println("could not open report directory / files for writing");
            System.exit(1);
        }
    }

    // Major work: process input files
    ImmutableList<Result> results = null;
    for (String in : cmd.getArgs()) {
        HeadlessRunDescription descr = HeadlessRunDescription.parse(in);
        logger.debug("invoking headless run...");
        BatchRunner runner = new BatchRunner();
        results = runner.runHeadless(descr);
        logger.debug("runHeadless returned " + results.size() + " results");
        // write results to the output stream as we go
        for (Result result : results) {
            outStream.println(result.toString());
        }
        outStream.flush();
    }
    outStream.close();

    // Write report files if requested
    if (cmd.hasOption("r") && results != null) {
        Reporter kermit = new Reporter(results);
        summaryFile.write(kermit.getSummary());
        summaryFile.close();
        byURLFile.write(kermit.getByURL());
        byURLFile.close();
        byRuleFile.write(kermit.getByRule());
        byRuleFile.close();
    }
}