Example usage for java.io OutputStreamWriter OutputStreamWriter

List of usage examples for java.io OutputStreamWriter OutputStreamWriter

Introduction

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

Prototype

public OutputStreamWriter(OutputStream out) 

Source Link

Document

Creates an OutputStreamWriter that uses the default character encoding.

Usage

From source file:SendMail.java

public static void main(String[] args) {
    try {//from   w  w  w . j  ava2s.  co  m
        // If the user specified a mailhost, tell the system about it.
        if (args.length >= 1)
            System.getProperties().put("mail.host", args[0]);

        // A Reader stream to read from the console
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        // Ask the user for the from, to, and subject lines
        System.out.print("From: ");
        String from = in.readLine();
        System.out.print("To: ");
        String to = in.readLine();
        System.out.print("Subject: ");
        String subject = in.readLine();

        // Establish a network connection for sending mail
        URL u = new URL("mailto:" + to); // Create a mailto: URL
        URLConnection c = u.openConnection(); // Create its URLConnection
        c.setDoInput(false); // Specify no input from it
        c.setDoOutput(true); // Specify we'll do output
        System.out.println("Connecting..."); // Tell the user
        System.out.flush(); // Tell them right now
        c.connect(); // Connect to mail host
        PrintWriter out = // Get output stream to host
                new PrintWriter(new OutputStreamWriter(c.getOutputStream()));

        // We're talking to the SMTP server now.
        // Write out mail headers. Don't let users fake the From address
        out.print("From: \"" + from + "\" <" + System.getProperty("user.name") + "@"
                + InetAddress.getLocalHost().getHostName() + ">\r\n");
        out.print("To: " + to + "\r\n");
        out.print("Subject: " + subject + "\r\n");
        out.print("\r\n"); // blank line to end the list of headers

        // Now ask the user to enter the body of the message
        System.out.println("Enter the message. " + "End with a '.' on a line by itself.");
        // Read message line by line and send it out.
        String line;
        for (;;) {
            line = in.readLine();
            if ((line == null) || line.equals("."))
                break;
            out.print(line + "\r\n");
        }

        // Close (and flush) the stream to terminate the message
        out.close();
        // Tell the user it was successfully sent.
        System.out.println("Message sent.");
    } catch (Exception e) { // Handle any exceptions, print error message.
        System.err.println(e);
        System.err.println("Usage: java SendMail [<mailhost>]");
    }
}

From source file:Base64Stuff.java

public static void main(String[] args) {
    //Random random = new Random();
    try {//  w w  w .j  a va  2  s  . co  m
        File file1 = new File("C:\\\\Program Files\\\\ImageJ\\\\images\\\\confocal-series-10001.tif");
        //File file2 = new File("C:\\Program Files\\ImageJ\\images\\confocal-series-10000.tif");
        ImagePlus image1 = new ImagePlus(
                "C:\\\\Program Files\\\\ImageJ\\\\images\\\\confocal-series-10001.tif");
        //ImagePlus image2 = new ImagePlus("C:\\Program Files\\ImageJ\\images\\two.tif");

        byte[] myBytes1 = org.apache.commons.io.FileUtils.readFileToByteArray(file1);
        //byte[] myBytes2 = org.apache.commons.io.FileUtils.readFileToByteArray(file2);
        //random.nextBytes(randomBytes);

        //String internalVersion1 = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(myBytes1);
        //String internalVersion2 = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(myBytes2);
        byte[] apacheBytes1 = org.apache.commons.codec.binary.Base64.encodeBase64(myBytes1);
        //byte[] apacheBytes2 =  org.apache.commons.codec.binary.Base64.encodeBase64(myBytes2);
        String string1 = new String(apacheBytes1);
        //String string2 = new String(apacheBytes2);

        System.out.println("File1 length:" + string1.length());
        //System.out.println("File2 length:" + string2.length());
        System.out.println(string1);
        //System.out.println(string2);

        System.out.println("Image1 size: (" + image1.getWidth() + "," + image1.getHeight() + ")");
        //System.out.println("Image2 size: (" + image2.getWidth() + "," + image2.getHeight() + ")");

        String urlParameters = "data=" + string1 + "&size=1000x1000";

        URL url = new URL("http://api.qrserver.com/v1/create-qr-code/");
        URLConnection conn = url.openConnection();

        conn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        writer.write(urlParameters);
        writer.flush();

        //byte buf[] = new byte[700000000];

        BufferedInputStream reader = new BufferedInputStream(conn.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream("C:\\Users\\expertoweb\\Desktop\\qrcode2.png"));

        int data;
        while ((data = reader.read()) != -1) {
            bos.write(data);
        }

        writer.close();
        reader.close();
        bos.close();

    } catch (IOException e) {
    }
}

From source file:org.apiwatch.cli.APIScan.java

public static void main(String[] argv) {
    try {// www. j  av a  2  s . c  o m
        Namespace args = parseArgs(argv);

        Logger log = Logger.getLogger(APIDiff.class.getName());

        log.trace("Finding files to analyse...");
        DirectoryWalker walker = new DirectoryWalker(args.<String>getList(Args.EXCLUDES_OPTION),
                args.<String>getList(Args.INCLUDES_OPTION));

        Set<String> files = walker.walk(args.<String>getList(INPUT_PATHS));
        APIScope scope = Analyser.analyse(files, args.getAttrs());

        if (args.get(OUTPUT_LOCATION) != null) {
            IO.putAPIData(scope, args.getString(Args.OUTPUT_FORMAT_OPTION),
                    args.getString(Analyser.ENCODING_OPTION), args.getString(OUTPUT_LOCATION),
                    args.getString(Args.USERNAME_OPTION), args.getString(Args.PASSWORD_OPTION));
        } else {
            OutputStreamWriter writer = new OutputStreamWriter(System.out);
            Serializers.dumpAPIScope(scope, writer, args.getString(Args.OUTPUT_FORMAT_OPTION));
            writer.flush();
            writer.close();
        }
    } catch (HttpException e) {
        Logger.getLogger(APIDiff.class.getName()).error(e.getMessage());
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:io.minimum.minecraft.rbclean.RedisBungeeClean.java

public static void main(String... args) {
    Options options = new Options();

    Option hostOption = new Option("h", "host", true, "Sets the Redis host to use.");
    hostOption.setRequired(true);/*  ww  w  . j  a v  a 2s.  c  o m*/
    options.addOption(hostOption);

    Option portOption = new Option("p", "port", true, "Sets the Redis port to use.");
    options.addOption(portOption);

    Option passwordOption = new Option("w", "password", true, "Sets the Redis password to use.");
    options.addOption(passwordOption);

    Option dryRunOption = new Option("d", "dry-run", false, "Performs a dry run (no data is modified).");
    options.addOption(dryRunOption);

    CommandLine commandLine;

    try {
        commandLine = new DefaultParser().parse(options, args);
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("RedisBungeeClean", options);
        return;
    }

    int port = commandLine.hasOption('p') ? Integer.parseInt(commandLine.getOptionValue('p')) : 6379;

    try (Jedis jedis = new Jedis(commandLine.getOptionValue('h'), port, 0)) {
        if (commandLine.hasOption('w')) {
            jedis.auth(commandLine.getOptionValue('w'));
        }

        System.out.println("Fetching UUID cache...");
        Map<String, String> uuidCache = jedis.hgetAll("uuid-cache");
        Gson gson = new Gson();

        // Just in case we need it, compress everything in JSON format.
        if (!commandLine.hasOption('d')) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
            File file = new File("uuid-cache-previous-" + dateFormat.format(new Date()) + ".json.gz");
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.out.println("Can't write backup of the UUID cache, will NOT proceed.");
                e.printStackTrace();
                return;
            }

            System.out.println("Creating backup (as " + file.getName() + ")...");

            try (OutputStreamWriter bw = new OutputStreamWriter(
                    new GZIPOutputStream(new FileOutputStream(file)))) {
                gson.toJson(uuidCache, bw);
            } catch (IOException e) {
                System.out.println("Can't write backup of the UUID cache, will NOT proceed.");
                e.printStackTrace();
                return;
            }
        }

        System.out.println("Cleaning out the bird cage (this may take a while...)");
        int originalSize = uuidCache.size();
        for (Iterator<Map.Entry<String, String>> it = uuidCache.entrySet().iterator(); it.hasNext();) {
            CachedUUIDEntry entry = gson.fromJson(it.next().getValue(), CachedUUIDEntry.class);

            if (entry.expired()) {
                it.remove();
            }
        }
        int newSize = uuidCache.size();

        if (commandLine.hasOption('d')) {
            System.out.println(
                    (originalSize - newSize) + " records would be expunged if a dry run was not conducted.");
        } else {
            System.out.println("Expunging " + (originalSize - newSize) + " records...");
            Transaction transaction = jedis.multi();
            transaction.del("uuid-cache");
            transaction.hmset("uuid-cache", uuidCache);
            transaction.exec();
            System.out.println("Expunging complete.");
        }
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.CollectionDiffer.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("i1", null, true, "Input file 1");
    options.addOption("i2", null, true, "Input file 2");
    options.addOption("o", null, true, "Output file");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {//from ww w.j  av  a 2 s  .c  o  m
        CommandLine cmd = parser.parse(options, args);

        InputStream input1 = null, input2 = null;

        if (cmd.hasOption("i1")) {
            input1 = CompressUtils.createInputStream(cmd.getOptionValue("i1"));
        } else {
            Usage("Specify 'Input file 1'");
        }
        if (cmd.hasOption("i2")) {
            input2 = CompressUtils.createInputStream(cmd.getOptionValue("i2"));
        } else {
            Usage("Specify 'Input file 2'");
        }

        HashSet<String> hSubj = new HashSet<String>();

        BufferedWriter out = null;

        if (cmd.hasOption("o")) {
            String outFile = cmd.getOptionValue("o");

            out = new BufferedWriter(new OutputStreamWriter(CompressUtils.createOutputStream(outFile)));
        } else {
            Usage("Specify 'Output file'");
        }

        XmlIterator inpIter2 = new XmlIterator(input2, YahooAnswersReader.DOCUMENT_TAG);

        int docNum = 1;
        for (String oneRec = inpIter2.readNext(); !oneRec.isEmpty(); oneRec = inpIter2.readNext(), ++docNum) {
            if (docNum % 10000 == 0) {
                System.out.println(String.format(
                        "Loaded and memorized questions for %d documents from the second input file", docNum));
            }
            ParsedQuestion q = YahooAnswersParser.parse(oneRec, false);
            hSubj.add(q.mQuestion);
        }

        XmlIterator inpIter1 = new XmlIterator(input1, YahooAnswersReader.DOCUMENT_TAG);

        System.out.println("=============================================");
        System.out.println("Memoization is done... now let's diff!!!");
        System.out.println("=============================================");

        docNum = 1;
        int skipOverlapQty = 0, skipErrorQty = 0;
        for (String oneRec = inpIter1.readNext(); !oneRec.isEmpty(); ++docNum, oneRec = inpIter1.readNext()) {
            if (docNum % 10000 == 0) {
                System.out.println(String.format("Processed %d documents from the first input file", docNum));
            }

            oneRec = oneRec.trim() + System.getProperty("line.separator");

            ParsedQuestion q = null;
            try {
                q = YahooAnswersParser.parse(oneRec, false);
            } catch (Exception e) {
                // If <bestanswer>...</bestanswer> is missing we may end up here...
                // This is a bit funny, because this element is supposed to be mandatory,
                // but it's not.
                System.err.println("Skipping due to parsing error, exception: " + e);
                skipErrorQty++;
                continue;
            }
            if (hSubj.contains(q.mQuestion.trim())) {
                //System.out.println(String.format("Skipping uri='%s', question='%s'", q.mQuestUri, q.mQuestion));
                skipOverlapQty++;
                continue;
            }

            out.write(oneRec);
        }
        System.out.println(
                String.format("Processed %d documents, skipped because of overlap/errors %d/%d documents",
                        docNum - 1, skipOverlapQty, skipErrorQty));
        out.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:ChannelToWriter.java

public static void main(String[] args) throws IOException {
    FileChannel c = new FileInputStream(args[0]).getChannel();
    OutputStreamWriter w = new OutputStreamWriter(System.out);
    Charset utf8 = Charset.forName("UTF-8");
    ChannelToWriter.copy(c, w, utf8);//from   w  w  w.j  a  va2  s  . c om
    c.close();
    w.close();
}

From source file:org.apiwatch.cli.APIDiff.java

public static void main(String[] argv) {
    try {/*  w w w  .j  a va  2  s .c o  m*/
        Namespace args = parseArgs(argv);

        Logger log = Logger.getLogger(APIDiff.class.getName());

        @SuppressWarnings("unchecked")
        Map<String, Map<String, String>> rulesConfig = (Map<String, Map<String, String>>) args
                .get(Args.RULES_CONFIG_OPTION);
        if (rulesConfig != null) {
            RulesFinder.configureRules(rulesConfig);
        }

        log.trace("Deserializing API data...");
        APIScope scopeA = IO.getAPIData(args.getString(COMPONENT_A), args.getString(Args.INPUT_FORMAT_OPTION),
                args.getString(Analyser.ENCODING_OPTION), args.getString(Args.USERNAME_OPTION),
                args.getString(Args.PASSWORD_OPTION));
        APIScope scopeB = IO.getAPIData(args.getString(COMPONENT_B), args.getString(Args.INPUT_FORMAT_OPTION),
                args.getString(Analyser.ENCODING_OPTION), args.getString(Args.USERNAME_OPTION),
                args.getString(Args.PASSWORD_OPTION));

        log.trace("Calculation of differences...");
        List<APIDifference> diffs = DifferencesCalculator.getDiffs(scopeA, scopeB);

        log.trace("Detection of API stability violations...");
        ViolationsCalculator violationsClac = new ViolationsCalculator(RulesFinder.rules().values());

        Severity threshold = (Severity) args.get(Args.SEVERITY_THRESHOLD_OPTION);
        List<APIStabilityViolation> violations = violationsClac.getViolations(diffs, threshold);

        OutputStreamWriter writer = new OutputStreamWriter(System.out);
        Serializers.dumpViolations(violations, writer, args.getString(Args.OUTPUT_FORMAT_OPTION));
        writer.flush();
        writer.close();
    } catch (HttpException e) {
        Logger.getLogger(APIDiff.class.getName()).error(e.getMessage());
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

}

From source file:org.apiwatch.cli.APIWatch.java

public static void main(String[] argv) {
    try {/*from   w  ww.  j  a v a  2  s.  c  o  m*/
        Namespace args = parseArgs(argv);

        Logger log = Logger.getLogger(APIWatch.class.getName());

        @SuppressWarnings("unchecked")
        Map<String, Map<String, String>> rulesConfig = (Map<String, Map<String, String>>) args
                .get(Args.RULES_CONFIG_OPTION);
        if (rulesConfig != null) {
            RulesFinder.configureRules(rulesConfig);
        }

        APIScope referenceScope = IO.getAPIData(args.getString(REFERENCE_API_DATA),
                args.getString(Args.INPUT_FORMAT_OPTION), args.getString(Analyser.ENCODING_OPTION),
                args.getString(Args.USERNAME_OPTION), args.getString(Args.PASSWORD_OPTION));

        DirectoryWalker walker = new DirectoryWalker(args.<String>getList(Args.EXCLUDES_OPTION),
                args.<String>getList(Args.INCLUDES_OPTION));

        Set<String> files = walker.walk(args.<String>getList(INPUT_PATHS));
        APIScope newScope = Analyser.analyse(files, args.getAttrs());

        log.trace("Calculation of differences...");
        List<APIDifference> diffs = DifferencesCalculator.getDiffs(referenceScope, newScope);

        log.trace("Detection of API stability violations...");
        ViolationsCalculator violationsClac = new ViolationsCalculator(RulesFinder.rules().values());

        Severity threshold = (Severity) args.get(Args.SEVERITY_THRESHOLD_OPTION);
        List<APIStabilityViolation> violations = violationsClac.getViolations(diffs, threshold);

        OutputStreamWriter writer = new OutputStreamWriter(System.out);
        Serializers.dumpViolations(violations, writer, args.getString(Args.OUTPUT_FORMAT_OPTION));
        writer.flush();
        writer.close();

        log.info(violations.size() + " violations.");
    } catch (HttpException e) {
        Logger.getLogger(APIWatch.class.getName()).error(e.getMessage());
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.foudroyantfactotum.mod.fousarchive.utility.midi.FileSupporter.java

public static void main(String[] args) throws InterruptedException, IOException {
    for (int i = 0; i < noOfWorkers; ++i)
        pool.submit(new ConMidiDetailsPuller());

    final File sourceDir = new File(source);
    final File outputDir = new File(output);

    Logger.info(UserLogger.GENERAL, "source directory: " + sourceDir.getAbsolutePath());
    Logger.info(UserLogger.GENERAL, "output directory: " + outputDir.getAbsolutePath());
    Logger.info(UserLogger.GENERAL, "processing midi files using " + noOfWorkers + " cores");

    FileUtils.deleteDirectory(outputDir);
    FileUtils.touch(new File(outputDir + "/master.json.gz"));

    for (File sfile : sourceDir.listFiles()) {
        recFile(sfile, files);/*from   ww w. j av a  2s .  c  o  m*/
    }

    for (int i = 0; i < noOfWorkers; ++i)
        files.put(TERMINATOR);

    pool.shutdown();
    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);//just get all the work done first.

    try (final OutputStream fstream = new FileOutputStream(outputDir + "/master.json.gz")) {
        try (final GZIPOutputStream gzstream = new GZIPOutputStream(fstream)) {
            final OutputStreamWriter osw = new OutputStreamWriter(gzstream);

            osw.write(JSON.toJson(processedMidiFiles));
            osw.flush();
        }
    } catch (IOException e) {
        Logger.info(UserLogger.GENERAL, e.toString());
    }

    Logger.info(UserLogger.GENERAL, "Processed " + processedMidiFiles.size() + " midi files out of " + fileCount
            + " files. " + (fileCount - processedMidiFiles.size()) + " removed");
}

From source file:at.newmedialab.ldpath.template.LDTemplate.java

public static void main(String[] args) {
    Options options = buildOptions();/* ww  w  .  j  a  va2s.  c om*/

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        Level logLevel = Level.WARN;

        if (cmd.hasOption("loglevel")) {
            String logLevelName = cmd.getOptionValue("loglevel");
            if ("DEBUG".equals(logLevelName.toUpperCase())) {
                logLevel = Level.DEBUG;
            } else if ("INFO".equals(logLevelName.toUpperCase())) {
                logLevel = Level.INFO;
            } else if ("WARN".equals(logLevelName.toUpperCase())) {
                logLevel = Level.WARN;
            } else if ("ERROR".equals(logLevelName.toUpperCase())) {
                logLevel = Level.ERROR;
            } else {
                log.error("unsupported log level: {}", logLevelName);
            }
        }

        if (logLevel != null) {
            for (String logname : new String[] { "at", "org", "net", "com" }) {

                ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
                        .getLogger(logname);
                logger.setLevel(logLevel);
            }
        }

        File template = null;
        if (cmd.hasOption("template")) {
            template = new File(cmd.getOptionValue("template"));
        }

        GenericSesameBackend backend;
        if (cmd.hasOption("store")) {
            backend = new LDPersistentBackend(new File(cmd.getOptionValue("store")));
        } else {
            backend = new LDMemoryBackend();
        }

        Resource context = null;
        if (cmd.hasOption("context")) {
            context = backend.getRepository().getValueFactory().createURI(cmd.getOptionValue("context"));
        }

        BufferedWriter out = null;
        if (cmd.hasOption("out")) {
            File of = new File(cmd.getOptionValue("out"));
            if (of.canWrite()) {
                out = new BufferedWriter(new FileWriter(of));
            } else {
                log.error("cannot write to output file {}", of);
                System.exit(1);
            }
        } else {
            out = new BufferedWriter(new OutputStreamWriter(System.out));
        }

        if (backend != null && context != null && template != null) {
            TemplateEngine<Value> engine = new TemplateEngine<Value>(backend);

            engine.setDirectoryForTemplateLoading(template.getParentFile());
            engine.processFileTemplate(context, template.getName(), out);
            out.flush();
            out.close();
        }

        if (backend instanceof LDPersistentBackend) {
            ((LDPersistentBackend) backend).shutdown();
        }

    } catch (ParseException e) {
        System.err.println("invalid arguments");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (FileNotFoundException e) {
        System.err.println("file or program could not be found");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (IOException e) {
        System.err.println("could not access file");
        e.printStackTrace(System.err);
    } catch (TemplateException e) {
        System.err.println("error while processing template");
        e.printStackTrace(System.err);
    }

}