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) throws FileNotFoundException 

Source Link

Document

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

Usage

From source file:org.apache.infra.reviewboard.ReviewBoard.java

public static void main(String... args) throws IOException {

    URL url = new URL(REVIEW_BOARD_URL);
    HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    Executor executor = Executor.newInstance().auth(host, REVIEW_BOARD_USERNAME, REVIEW_BOARD_PASSWORD)
            .authPreemptive(host);//from   w ww .ja v a  2 s  .co  m

    Request request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/");
    Response response = executor.execute(request);

    request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/");
    response = executor.execute(request);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode json = mapper.readTree(response.returnResponse().getEntity().getContent());

    JsonFactory factory = new JsonFactory();
    JsonGenerator generator = factory.createGenerator(new PrintWriter(System.out));
    generator.setPrettyPrinter(new DefaultPrettyPrinter());
    mapper.writeTree(generator, json);
}

From source file:com.aestel.chemistry.openEye.fp.DistMatrix.java

public static void main(String... args) throws IOException {
    long start = System.currentTimeMillis();

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("i", true, "input file [.tsv from FingerPrinter]");
    opt.setRequired(true);//from  www.  j  ava2s.  c o  m
    options.addOption(opt);

    opt = new Option("o", true, "outpur file [.tsv ");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (args.length != 0)
        exitWithHelp(options);

    String file = cmd.getOptionValue("i");
    BufferedReader in = new BufferedReader(new FileReader(file));

    file = cmd.getOptionValue("o");
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));

    ArrayList<Fingerprint> fps = new ArrayList<Fingerprint>();
    ArrayList<String> ids = new ArrayList<String>();
    String line;
    while ((line = in.readLine()) != null) {
        String[] parts = line.split("\t");
        if (parts.length == 3) {
            ids.add(parts[0]);
            fps.add(new ByteFingerprint(parts[2]));
        }
    }
    in.close();

    out.print("ID");
    for (int i = 0; i < ids.size(); i++) {
        out.print('\t');
        out.print(ids.get(i));
    }
    out.println();

    for (int i = 0; i < ids.size(); i++) {
        out.print(ids.get(i));
        Fingerprint fp1 = fps.get(i);

        for (int j = 0; j <= i; j++) {
            out.printf("\t%.4g", fp1.tanimoto(fps.get(j)));
        }
        out.println();
    }
    out.close();

    System.err.printf("Done %d fingerprints in %.2gsec\n", fps.size(),
            (System.currentTimeMillis() - start) / 1000D);
}

From source file:Reverse.java

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

    if (args.length != 1) {
        System.err.println("Usage:  java Reverse " + "string_to_reverse");
        System.exit(1);/*from   ww  w  .jav  a  2  s .  c o m*/
    }

    String stringToReverse = URLEncoder.encode(args[0]);

    URL url = new URL("http://java.sun.com/cgi-bin/backwards");
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());
    out.println("string=" + stringToReverse);
    out.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

    in.close();
}

From source file:UseConverters.java

public static void main(String[] args) {
    try {//from   w  ww  . ja  v a  2s .c  o  m
        BufferedReader fromKanji = new BufferedReader(
                new InputStreamReader(new FileInputStream("kanji.txt"), "EUC_JP"));
        PrintWriter toSwedish = new PrintWriter(new OutputStreamWriter( // XXX
                // check
                // enco
                new FileOutputStream("sverige.txt"), "ISO8859_3"));

        // reading and writing here...
        String line = fromKanji.readLine();
        System.out.println("-->" + line + "<--");
        toSwedish.println(line);
        fromKanji.close();
        toSwedish.close();
    } catch (UnsupportedEncodingException exc) {
        System.err.println("Bad encoding" + exc);
        return;
    } catch (IOException err) {
        System.err.println("I/O Error: " + err);
        return;
    }
}

From source file:ModifyModelSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
        model.addElement(labels[i]);/*from  ww w  . j  a  v a  2s.  co m*/
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    contentPane.add(scrollPane1, BorderLayout.WEST);

    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    JScrollPane scrollPane2 = new JScrollPane(textArea);
    contentPane.add(scrollPane2, BorderLayout.CENTER);

    ListDataListener listDataListener = new ListDataListener() {
        public void contentsChanged(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalAdded(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalRemoved(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        private void appendEvent(ListDataEvent listDataEvent) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            switch (listDataEvent.getType()) {
            case ListDataEvent.CONTENTS_CHANGED:
                pw.print("Type: Contents Changed");
                break;
            case ListDataEvent.INTERVAL_ADDED:
                pw.print("Type: Interval Added");
                break;
            case ListDataEvent.INTERVAL_REMOVED:
                pw.print("Type: Interval Removed");
                break;
            }
            pw.print(", Index0: " + listDataEvent.getIndex0());
            pw.print(", Index1: " + listDataEvent.getIndex1());
            DefaultListModel theModel = (DefaultListModel) listDataEvent.getSource();
            Enumeration elements = theModel.elements();
            pw.print(", Elements: ");
            while (elements.hasMoreElements()) {
                pw.print(elements.nextElement());
                pw.print(",");
            }
            pw.println();
            textArea.append(sw.toString());
        }
    };

    model.addListDataListener(listDataListener);

    // Setup buttons
    JPanel jp = new JPanel(new GridLayout(2, 1));
    JPanel jp1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
    JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
    jp.add(jp1);
    jp.add(jp2);
    JButton jb = new JButton("add F");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.add(0, "First");
        }
    });
    jb = new JButton("addElement L");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.addElement("Last");
        }
    });
    jb = new JButton("insertElementAt M");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            model.insertElementAt("Middle", size / 2);
        }
    });
    jb = new JButton("set F");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.set(0, "New First");
        }
    });
    jb = new JButton("setElementAt L");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.setElementAt("New Last", size - 1);
        }
    });
    jb = new JButton("load 10");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            for (int i = 0, n = labels.length; i < n; i++) {
                model.addElement(labels[i]);
            }
        }
    });
    jb = new JButton("clear");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.clear();
        }
    });
    jb = new JButton("remove F");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.remove(0);
        }
    });
    jb = new JButton("removeAllElements");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.removeAllElements();
        }
    });
    jb = new JButton("removeElement 'Last'");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.removeElement("Last");
        }
    });
    jb = new JButton("removeElementAt M");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.removeElementAt(size / 2);
        }
    });
    jb = new JButton("removeRange FM");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.removeRange(0, size / 2);
        }
    });
    contentPane.add(jp, BorderLayout.SOUTH);
    frame.setSize(640, 300);
    frame.setVisible(true);
}

From source file:PDFDemo.java

public static void main(String[] argv) throws IOException {
    PrintWriter pout;/*  ww w .jav a 2  s  .  c om*/
    if (argv.length == 0) {
        pout = new PrintWriter(System.out);
    } else {
        if (new File(argv[0]).exists()) {
            throw new IOException("Output file " + argv[0] + " already exists");
        }
        pout = new PrintWriter(new FileWriter(argv[0]));
    }
    PDF p = new PDF(pout);
    Page p1 = new Page(p);
    p1.add(new MoveTo(p, 100, 600));
    p1.add(new Text(p, "Hello world, live on the web."));
    p1.add(new Text(p, "Hello world, line 2 on the web."));
    p.add(p1);
    p.setAuthor("Ian F. Darwin");
    p.writePDF();
}

From source file:Connect.java

public static void main(String[] av) {
    String dbURL = "jdbc:odbc:Companies";
    try {//from ww w . j  a v a 2 s  .  c o m
        // Load the jdbc-odbc bridge driver
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        // Enable logging
        DriverManager.setLogWriter(new PrintWriter((System.err)));

        System.out.println("Getting Connection");
        Connection conn = DriverManager.getConnection(dbURL, "ian", ""); // user,
        // passwd

        // If a SQLWarning object is available, print its
        // warning(s). There may be multiple warnings chained.

        SQLWarning warn = conn.getWarnings();
        while (warn != null) {
            System.out.println("SQLState: " + warn.getSQLState());
            System.out.println("Message:  " + warn.getMessage());
            System.out.println("Vendor:   " + warn.getErrorCode());
            System.out.println("");
            warn = warn.getNextWarning();
        }

        // Do something with the connection here...

        conn.close(); // All done with that DB connection

    } catch (ClassNotFoundException e) {
        System.out.println("Can't load driver " + e);
    } catch (SQLException e) {
        System.out.println("Database access failed " + e);
    }
}

From source file:gov.nist.healthcare.ttt.webapp.api.GetCCDAFolderTest.java

public static void main(String[] args) throws Exception {
    long startTime = System.currentTimeMillis();
    JSONObject res = new JSONObject();
    HashMap<String, Object> json = new HashMap<>();
    String sha = getHTML(/*from   www.  j  a  v  a2s. c  om*/
            "https://api.github.com/repos/siteadmin/2015-Certification-C-CDA-Test-Data/branches/master")
                    .getJSONObject("commit").get("sha").toString();
    JSONArray filesArray = getHTML(
            "https://api.github.com/repos/siteadmin/2015-Certification-C-CDA-Test-Data/git/trees/" + sha
                    + "?recursive=1").getJSONArray("tree");

    HashMap<String, Object> resultMap = new HashMap<>();
    for (int i = 0; i < filesArray.length(); i++) {
        JSONObject file = filesArray.getJSONObject(i);
        if (!files2ignore.contains(file.get("path"))) {
            // Get path array
            String[] path = file.get("path").toString().split("/");
            //            System.out.println(String.join("/", path));
            //            for(String dir : path) {
            //               if(Pattern.matches(extensionRegex, dir)) {
            //                  System.out.println("File!! " + dir);
            //               }
            //            }
            //                        json = buildJson2(new HashMap<>(), path, false, true);
            //                        resultMap = deepMerge(resultMap, json);
            //                        System.out.println(new JSONObject(json).toString(2));
            buildJson3(resultMap, path);
        }

    }
    //      String[] test = {"test", "retest", "file.txt"};
    //      json = buildJson2(json, test, false, true);
    System.out.println(new JSONObject(resultMap).toString(2));
    PrintWriter out = new PrintWriter("filename.txt");
    out.println(new JSONObject(resultMap).toString(2));

    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    System.out.println("Running time: " + totalTime / 1000.0 + "s");

    // Try download
    //      URL website = new URL("https://raw.githubusercontent.com/siteadmin/2015-Certification-C-CDA-Test-Data/master/Receiver%20SUT%20Test%20Data/170.315_b1_ToC_Amb/170.315_b1_toc_amb_ccd_r11_sample1_v1.xml");
    //      InputStream strm = website.openStream();
    //      System.out.println(IOUtils.toString(strm));
}

From source file:com.cisco.dbds.utils.report.CustomReport.java

/**
 * The main method./*w  ww . j  a  v  a 2 s.  c  o m*/
 *
 * @param args the arguments
 * @throws FileNotFoundException the file not found exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ParseException the parse exception
 * @throws AddressException the address exception
 */
public static void main(String[] args)
        throws FileNotFoundException, IOException, ParseException, AddressException {

    // reportparsejson();
    String msg = reportparsejson();
    sendmail(msg);
    String eol = System.getProperty("line.separator");
    //msg=msg.replaceAll("</tr>", eol+"</tr>");
    msg = msg.replaceAll("<tr", eol + "<tr");
    msg = msg.replaceAll("</table>", eol + "</table>");
    msg = msg.replaceAll("<table", eol + "<table");
    new FileOutputStream(htmlfname).close();
    htmlfile = new PrintWriter(new BufferedWriter(new FileWriter(htmlfname, true)));

    htmlfile.print(msg);
    htmlfile.close();

    // String mailContent = "Hi All<br>"+
    // "Build Tag id: jenkins-CANEAS-Nightly-Completed-190 has been completed and the run reports  found in the link: http://10.78.216.52:8080/job/CANEAS-Nightly-Completed/190/cucumber-html-reports/"
    // + "<br>"
    // +
    //
    // "EDCS link for failure analysis Reasons: http://wwwin-eng.cisco.com/cgi-bin/edcs/edcs_info?3677074"
    // + "<br>"
    // +
    // "(will be updated soon for the Build: jenkins-CANEAS-Nightly-Completed-190 )"
    // + "<br><br>" + "Regards" + "<br>" + "SIT Automation TEAM"
    // + "<br>";
    // sendmail(mailContent);
}

From source file:com.leonarduk.finance.chart.PieChartFactory.java

/**
 * Starting point for the demo./* w  ww. ja  v  a 2  s  . c  o  m*/
 *
 * @param args
 *            ignored.
 */
public static void main(final String[] args) {
    final PieChartFactory factory = new PieChartFactory("Title");
    factory.put("A", 12.2).put("B", 13.2).put("C", 31.2);

    try {
        // write an HTML page incorporating the image with an image map
        final File file2 = new File("multipiechart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        // ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println(ChartDisplay.saveImageAsPngAndReturnHtmlLink("345", 400, 400, factory.buildChart()));
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (final IOException e) {
        System.out.println(e.toString());
    }

}