Example usage for java.io PrintWriter PrintWriter

List of usage examples for java.io PrintWriter PrintWriter

Introduction

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

Prototype

public PrintWriter(File file, Charset charset) throws IOException 

Source Link

Document

Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.

Usage

From source file:com.cloudera.knittingboar.conf.cmdline.ModelTrainerCmdLineDriver.java

public static void main(String[] args) throws Exception {
    mainToOutput(args, new PrintWriter(System.out, true));

    int rc = ToolRunner.run(new Configuration(), new ModelTrainerCmdLineDriver(), args);

    // Log, because been bitten before on daemon threads; sanity check
    System.out.println("Calling System.exit(" + rc + ")");
    System.exit(rc);//w w  w . j  a v a  2 s . c  o  m
}

From source file:edu.umass.cs.gnsclient.console.CommandLineInterface.java

/**
 * Starts the GNS command line interface (CLI) console
 *
 * @param args optional argument is -silent for no console output
 * @throws Exception//from  w  ww .  j a v a 2s . c om
 */
public static void main(String[] args) throws Exception {
    try {
        CommandLine parser = initializeOptions(args);
        if (parser.hasOption("help")) {
            printUsage();
            //System.out.println("-host and -port are required!");
            System.exit(1);
        }
        boolean silent = parser.hasOption("silent");
        boolean noDefaults = parser.hasOption("noDefaults");
        ConsoleReader consoleReader = new ConsoleReader(System.in, new PrintWriter(System.out, true));
        ConsoleModule module = new ConsoleModule(consoleReader);
        if (noDefaults) {
            module.setUseGnsDefaults(false);
            KeyPairUtils.removeDefaultGns();
        }
        module.setSilent(silent);
        if (!silent) {
            module.printString("GNS Client Version: " + GNSClientConfig.readBuildVersion() + "\n");
        }
        module.handlePrompt();
        System.exit(0);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:NewFingerServer.java

public static void main(String[] arguments) throws Exception {
    ServerSocketChannel sockChannel = ServerSocketChannel.open();
    sockChannel.configureBlocking(false);

    InetSocketAddress server = new InetSocketAddress("localhost", 79);
    ServerSocket socket = sockChannel.socket();
    socket.bind(server);//from ww w  . ja  v a 2 s . co  m

    Selector selector = Selector.open();
    sockChannel.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();
        Set keys = selector.selectedKeys();
        Iterator it = keys.iterator();
        while (it.hasNext()) {
            SelectionKey selKey = (SelectionKey) it.next();
            it.remove();
            if (selKey.isAcceptable()) {
                ServerSocketChannel selChannel = (ServerSocketChannel) selKey.channel();
                ServerSocket selSocket = selChannel.socket();
                Socket connection = selSocket.accept();

                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader is = new BufferedReader(isr);
                PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()), false);
                pw.println("NIO Finger Server");
                pw.flush();
                String outLine = null;
                String inLine = is.readLine();
                if (inLine.length() > 0) {
                    outLine = inLine;
                }
                readPlan(outLine, pw);
                pw.flush();
                pw.close();
                is.close();

                connection.close();
            }
        }
    }
}

From source file:com.ml.ira.algos.RunLogistic.java

public static void main(String[] args) throws Exception {
    mainToOutput(args, new PrintWriter(new OutputStreamWriter(System.out, Charsets.UTF_8), true));
}

From source file:com.memonews.mahout.sentiment.SentimentModelTester.java

public static void main(final String[] args) throws IOException {
    final SentimentModelTester runner = new SentimentModelTester();
    if (runner.parseArgs(args)) {
        runner.run(new PrintWriter(System.out, true));
    }//  w w  w .  jav  a 2s  .c  o m
}

From source file:csv.parser.CSVParser.java

@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
    String file_to_parse;//  w ww.  j av  a2s.  c  o m
    String[] val_array;
    file_to_parse = "./input/E-library-data-3.csv";
    //Build reader instance
    //Read CSV file
    CSVReader reader = new CSVReader(new FileReader(file_to_parse), ';', '"', 1);

    //Read all rows at once
    List<String[]> allRows = reader.readAll();

    //        Read CSV line by line and use the string array as you want
    for (String[] row : allRows) {
        for (int i = 0; i < row.length; i++) {
            //Removing all newlines, tabs and '&' characters(invalid XML character)
            row[i] = row[i].replaceAll("(\\r|\\n|\\r\\n)+", " ");
            row[i] = row[i].replaceAll(System.getProperty("line.separator"), "; ");
            row[i] = row[i].replaceAll("&", "and");
        }

        System.out.println(Arrays.toString(row));
    }
    //Get the input fields
    List<String[]> map = getMap();
    String[] field;
    //Numbering for folders, folderNum is incremented for each new file
    long folderNum;
    folderNum = 0;
    for (String[] row : allRows) {
        //Creating new folder
        File file1 = new File("./output//newdir//folder" + folderNum + "");
        file1.mkdirs();
        //Creating content file
        PrintWriter writer_content = new PrintWriter("./output//newdir//folder" + folderNum + "//contents",
                "UTF-16");
        //Creating metadata_lrmi.xml
        PrintWriter writer_lrmi = new PrintWriter(
                "./output//newdir//folder" + folderNum + "//metadata_lrmi.xml", "UTF-16");
        //Creating content.xml
        PrintWriter writer = new PrintWriter("./output//newdir//folder" + folderNum + "//content.xml",
                "UTF-16");
        writer.println("<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"no\"?>");
        writer.println("<dublin_core schema=\"dc\">");
        writer_lrmi.println("<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"no\"?>");
        writer_lrmi.println("<dublin_core shema=\"lrmi\">");
        for (int i = 0; i < row.length; i++) {
            //After snooping data, we have to change these setting for each new csv file, as the data fileds are many times mismatched
            //These if-else statements take care of mismatched steps.
            if (i == 43) {
                continue;
            } else if (i == 43) {
                field = map.get(42);
            } else if (i == 44) {
                field = map.get(43);
            } else if (i == 45 || i == 46) {
                continue;
            } else {
                field = map.get(i);
            }
            //Separate multiple values
            val_array = parseVal(row[i]);
            //                if (val_array.length == 0) {
            //                    continue;
            //                }
            PrintWriter useWriter = writer;
            if (field[0].equals("lrmi")) {
                useWriter = writer_lrmi;
            }
            switch (field.length) {
            case 2:
                writeXML(useWriter, field[1], "", val_array);
                break;
            case 3:
                writeXML(useWriter, field[1], field[2], val_array);
                break;
            default:

            }
        }
        folderNum++;
        writer.println("</dublin_core>");
        writer_lrmi.println("</dublin_core>");
        writer.close();
        writer_lrmi.close();
        writer_content.close();
    }
}

From source file:TrainLogistic.java

public static void main(String[] args) throws Exception {
    long start = System.currentTimeMillis();
    mainToOutput(args, new PrintWriter(System.out, true));
    System.out.printf("time:%.2f s\n", (double) (System.currentTimeMillis() - start) / 1000.0);
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step7aLearningDataProducer.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
    String inputDir = args[0];/* w  ww  . ja v a 2  s  .  c om*/
    File outputDir = new File(args[1]);

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    Collection<File> files = IOHelper.listXmlFiles(new File(inputDir));

    // for generating ConvArgStrict use this
    String prefix = "no-eq_DescendingScoreArgumentPairListSorter";

    // for oversampling using graph transitivity properties use this
    //        String prefix = "generated_no-eq_AscendingScoreArgumentPairListSorter";

    Iterator<File> iterator = files.iterator();
    while (iterator.hasNext()) {
        File file = iterator.next();

        if (!file.getName().startsWith(prefix)) {
            iterator.remove();
        }
    }

    int totalGoldPairsCounter = 0;

    Map<String, Integer> goldDataDistribution = new HashMap<>();

    DescriptiveStatistics statsPerTopic = new DescriptiveStatistics();

    int totalPairsWithReasonSameAsGold = 0;

    DescriptiveStatistics ds = new DescriptiveStatistics();

    for (File file : files) {
        List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream()
                .fromXML(file);

        int pairsPerTopicCounter = 0;

        String name = file.getName().replaceAll(prefix, "").replaceAll("\\.xml", "");

        PrintWriter pw = new PrintWriter(new File(outputDir, name + ".csv"), "utf-8");

        pw.println("#id\tlabel\ta1\ta2");

        for (AnnotatedArgumentPair argumentPair : argumentPairs) {
            String goldLabel = argumentPair.getGoldLabel();

            if (!goldDataDistribution.containsKey(goldLabel)) {
                goldDataDistribution.put(goldLabel, 0);
            }

            goldDataDistribution.put(goldLabel, goldDataDistribution.get(goldLabel) + 1);

            pw.printf(Locale.ENGLISH, "%s\t%s\t%s\t%s%n", argumentPair.getId(), goldLabel,
                    multipleParagraphsToSingleLine(argumentPair.getArg1().getText()),
                    multipleParagraphsToSingleLine(argumentPair.getArg2().getText()));

            pairsPerTopicCounter++;

            int sameInOnePair = 0;

            // get gold reason statistics
            for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) {
                String label = assignment.getValue();

                if (goldLabel.equals(label)) {
                    sameInOnePair++;
                }
            }

            ds.addValue(sameInOnePair);
            totalPairsWithReasonSameAsGold += sameInOnePair;
        }

        totalGoldPairsCounter += pairsPerTopicCounter;
        statsPerTopic.addValue(pairsPerTopicCounter);

        pw.close();
    }

    System.out.println("Total reasons matching gold " + totalPairsWithReasonSameAsGold);
    System.out.println(ds);

    System.out.println("Total gold pairs: " + totalGoldPairsCounter);
    System.out.println(statsPerTopic);

    int totalPairs = 0;
    for (Integer pairs : goldDataDistribution.values()) {
        totalPairs += pairs;
    }
    System.out.println("Total pairs: " + totalPairs);
    System.out.println(goldDataDistribution);

}

From source file:EchoClient.java

 public static void main(String[] args) throws IOException {

     Socket echoSocket = null;/* w w  w . j  ava 2  s .c o m*/
     PrintWriter out = null;
     BufferedReader in = null;

     try {
         echoSocket = new Socket("taranis", 7);
         out = new PrintWriter(echoSocket.getOutputStream(), true);
         in = new BufferedReader(new InputStreamReader(
                                     echoSocket.getInputStream()));
     } catch (UnknownHostException e) {
         System.err.println("Don't know about host: taranis.");
         System.exit(1);
     } catch (IOException e) {
         System.err.println("Couldn't get I/O for "
                            + "the connection to: taranis.");
         System.exit(1);
     }

BufferedReader stdIn = new BufferedReader(
                                new InputStreamReader(System.in));
String userInput;

while ((userInput = stdIn.readLine()) != null) {
    out.println(userInput);
    System.out.println("echo: " + in.readLine());
}

out.close();
in.close();
stdIn.close();
echoSocket.close();
 }

From source file:com.ifeng.sorter.NginxApp.java

public static void main(String[] args) {

    String input = "src/test/resources/data/nginx_report.txt";

    PrintWriter pw = null;/*  w  w w .  j av  a 2s  .co m*/

    Map<String, List<LogBean>> resultMap = new HashMap<String, List<LogBean>>();
    List<String> ips = new ArrayList<String>();

    try {
        List<String> lines = FileUtils.readLines(new File(input));
        List<LogBean> items = new ArrayList<LogBean>();

        for (String line : lines) {
            String[] values = line.split("\t");

            if (values != null && values.length == 3) {// ip total seria
                try {
                    String ip = values[0].trim();
                    String total = values[1].trim();
                    String seria = values[2].trim();

                    LogBean bean = new LogBean(ip, Integer.parseInt(total), seria);

                    items.add(bean);

                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }

        Collections.sort(items);

        for (LogBean bean : items) {
            String key = bean.getIp();

            if (resultMap.containsKey(key)) {
                resultMap.get(key).add(bean);
            } else {
                List<LogBean> keyList = new ArrayList<LogBean>();
                keyList.add(bean);
                resultMap.put(key, keyList);

                ips.add(key);
            }
        }

        pw = new PrintWriter("src/test/resources/output/result.txt", "UTF-8");

        for (String ip : ips) {
            List<LogBean> list = resultMap.get(ip);

            for (LogBean bean : list) {
                pw.append(bean.toString());
                pw.println();
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        pw.flush();
        pw.close();
    }
}