Example usage for java.io PrintWriter print

List of usage examples for java.io PrintWriter print

Introduction

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

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:Main.java

public static void main(String[] args) {
    Object obj1 = "Object";
    Object obj2 = 2;/* w  w  w. ja v  a2 s. c  om*/
    Date date = new Date();
    try {
        PrintWriter pw = new PrintWriter(System.out);

        // print object
        pw.print(obj1);

        // print another object
        pw.print(obj2);

        // print a date (it is an object)
        pw.print(date);

        pw.flush();

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

From source file:Main.java

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

        PrintWriter pw = new PrintWriter(System.out);

        // print a boolean
        pw.print(true);

        // change the line
        pw.println();

        // print another boolean
        pw.print(bool);

        // flush the writer
        pw.flush();

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

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

    String hostName = "hostName";
    String fileName = "fileName";

    SSLSocket sslsock = (SSLSocket) factory.createSocket(hostName, 443);

    SSLSession session = sslsock.getSession();
    X509Certificate cert;//w ww . ja  v a2 s  . c  o  m
    try {
        cert = (X509Certificate) session.getPeerCertificates()[0];
    } catch (SSLPeerUnverifiedException e) {
        System.err.println(session.getPeerHost() + " did not present a valid certificate.");
        return;
    }

    System.out.println(session.getPeerHost() + " has presented a certificate belonging to:");
    Principal p = cert.getSubjectDN();
    System.out.println("\t[" + p.getName() + "]");
    System.out.println("The certificate bears the valid signature of:");
    System.out.println("\t[" + cert.getIssuerDN().getName() + "]");

    System.out.print("Do you trust this certificate (y/n)? ");
    System.out.flush();
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
    if (Character.toLowerCase(console.readLine().charAt(0)) != 'y')
        return;

    PrintWriter out = new PrintWriter(sslsock.getOutputStream());

    out.print("GET " + fileName + " HTTP/1.0\r\n\r\n");
    out.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream()));
    String line;
    while ((line = in.readLine()) != null)
        System.out.println(line);

    sslsock.close();
}

From source file:MainClass.java

public static void main(String[] args) {
    try {/*  w  w w  .  j a  v  a2s . c o m*/
        FileWriter fw = new FileWriter("LPT1:");

        PrintWriter pw = new PrintWriter(fw);
        String s = "www.java2s.com";

        int i, len = s.length();

        for (i = 0; len > 80; i += 80) {
            pw.print(s.substring(i, i + 80));
            pw.print("\r\n");
            len -= 80;
        }

        if (len > 0) {
            pw.print(s.substring(i));
            pw.print("\r\n");
        }

        pw.close();
    } catch (IOException e) {
        System.out.println(e);
    }
}

From source file:BookRank.java

/** Grab the sales rank off the web page and log it. */
public static void main(String[] args) throws Exception {

    Properties p = new Properties();
    String title = p.getProperty("title", "NO TITLE IN PROPERTIES");
    // The url must have the "isbn=" at the very end, or otherwise
    // be amenable to being string-catted to, like the default.
    String url = p.getProperty("url", "http://test.ing/test.cgi?isbn=");
    // The 10-digit ISBN for the book.
    String isbn = p.getProperty("isbn", "0000000000");
    // The RE pattern (MUST have ONE capture group for the number)
    String pattern = p.getProperty("pattern", "Rank: (\\d+)");

    // Looking for something like this in the input:
    //    <b>QuickBookShop.web Sales Rank: </b>
    //    26,252// w  w w .j a v  a  2  s .  c  om
    //    </font><br>

    Pattern r = Pattern.compile(pattern);

    // Open the URL and get a Reader from it.
    BufferedReader is = new BufferedReader(new InputStreamReader(new URL(url + isbn).openStream()));
    // Read the URL looking for the rank information, as
    // a single long string, so can match RE across multi-lines.
    String input = "input from console";
    // System.out.println(input);

    // If found, append to sales data file.
    Matcher m = r.matcher(input);
    if (m.find()) {
        PrintWriter pw = new PrintWriter(new FileWriter(DATA_FILE, true));
        String date = // `date +'%m %d %H %M %S %Y'`;
                new SimpleDateFormat("MM dd hh mm ss yyyy ").format(new Date());
        // Paren 1 is the digits (and maybe ','s) that matched; remove comma
        Matcher noComma = Pattern.compile(",").matcher(m.group(1));
        pw.println(date + noComma.replaceAll(""));
        pw.close();
    } else {
        System.err.println("WARNING: pattern `" + pattern + "' did not match in `" + url + isbn + "'!");
    }

    // Whether current data found or not, draw the graph, using
    // external plotting program against all historical data.
    // Could use gnuplot, R, any other math/graph program.
    // Better yet: use one of the Java plotting APIs.

    String gnuplot_cmd = "set term png\n" + "set output \"" + GRAPH_FILE + "\"\n" + "set xdata time\n"
            + "set ylabel \"Book sales rank\"\n" + "set bmargin 3\n" + "set logscale y\n"
            + "set yrange [1:60000] reverse\n" + "set timefmt \"%m %d %H %M %S %Y\"\n" + "plot \"" + DATA_FILE
            + "\" using 1:7 title \"" + title + "\" with lines\n";

    Process proc = Runtime.getRuntime().exec("/usr/local/bin/gnuplot");
    PrintWriter gp = new PrintWriter(proc.getOutputStream());
    gp.print(gnuplot_cmd);
    gp.close();
}

From source file:Connect.java

public static void main(String[] args) {
    try { // Handle exceptions below
        // Get our command-line arguments
        String hostname = args[0];
        int port = Integer.parseInt(args[1]);
        String message = "";
        if (args.length > 2)
            for (int i = 2; i < args.length; i++)
                message += args[i] + " ";

        // Create a Socket connected to the specified host and port.
        Socket s = new Socket(hostname, port);

        // Get the socket output stream and wrap a PrintWriter around it
        PrintWriter out = new PrintWriter(s.getOutputStream());

        // Sent the specified message through the socket to the server.
        out.print(message + "\r\n");
        out.flush(); // Send it now.

        // Get an input stream from the socket and wrap a BufferedReader
        // around it, so we can read lines of text from the server.
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        // Before we start reading the server's response tell the socket
        // that we don't want to wait more than 3 seconds
        s.setSoTimeout(3000);/*from w w w  .  jav  a  2 s. c o m*/

        // Now read lines from the server until the server closes the
        // connection (and we get a null return indicating EOF) or until
        // the server is silent for 3 seconds.
        try {
            String line;
            while ((line = in.readLine()) != null)
                // If we get a line
                System.out.println(line); // print it out.
        } catch (SocketTimeoutException e) {
            // We end up here if readLine() times out.
            System.err.println("Timeout; no response from server.");
        }

        out.close(); // Close the output stream
        in.close(); // Close the input stream
        s.close(); // Close the socket
    } catch (IOException e) { // Handle IO and network exceptions here
        System.err.println(e);
    } catch (NumberFormatException e) { // Bad port number
        System.err.println("You must specify the port as a number");
    } catch (ArrayIndexOutOfBoundsException e) { // wrong # of args
        System.err.println("Usage: Connect <hostname> <port> message...");
    }
}

From source file:HttpMirror.java

public static void main(String args[]) {
    try {//from   w w  w  .  j av a2s  .com
        // Get the port to listen on
        int port = Integer.parseInt(args[0]);
        // Create a ServerSocket to listen on that port.
        ServerSocket ss = new ServerSocket(port);
        // Now enter an infinite loop, waiting for & handling connections.
        for (;;) {
            // Wait for a client to connect. The method will block;
            // when it returns the socket will be connected to the client
            Socket client = ss.accept();

            // Get input and output streams to talk to the client
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream());

            // Start sending our reply, using the HTTP 1.1 protocol
            out.print("HTTP/1.1 200 \r\n"); // Version & status code
            out.print("Content-Type: text/plain\r\n"); // The type of data
            out.print("Connection: close\r\n"); // Will close stream
            out.print("\r\n"); // End of headers

            // Now, read the HTTP request from the client, and send it
            // right back to the client as part of the body of our
            // response. The client doesn't disconnect, so we never get
            // an EOF. It does sends an empty line at the end of the
            // headers, though. So when we see the empty line, we stop
            // reading. This means we don't mirror the contents of POST
            // requests, for example. Note that the readLine() method
            // works with Unix, Windows, and Mac line terminators.
            String line;
            while ((line = in.readLine()) != null) {
                if (line.length() == 0)
                    break;
                out.print(line + "\r\n");
            }

            // Close socket, breaking the connection to the client, and
            // closing the input and output streams
            out.close(); // Flush and close the output stream
            in.close(); // Close the input stream
            client.close(); // Close the socket itself
        } // Now loop again, waiting for the next connection
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java HttpMirror <port>");
    }
}

From source file:Main.java

public static void main(String[] args) {
    Object obj1 = "Object";
    Object obj2 = 2;/*from   w ww. j  av  a 2  s  . co m*/
    Date date = new Date();
    try {

        PrintWriter pw = new PrintWriter(System.out);

        // print object
        pw.println(obj1);

        // print another object
        pw.println(obj2);

        // print a date (it is an object)
        pw.print(date);

        // flush the writer
        pw.flush();

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

From source file:SelectingComboSample.java

public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "J", "I" };
    JFrame frame = new JFrame("Selecting JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    JComboBox comboBox = new JComboBox(labels);
    contentPane.add(comboBox, BorderLayout.SOUTH);

    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);/* www .  j  a va2  s  .  c o  m*/
    JScrollPane sp = new JScrollPane(textArea);
    contentPane.add(sp, BorderLayout.CENTER);

    ItemListener itemListener = new ItemListener() {
        public void itemStateChanged(ItemEvent itemEvent) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            int state = itemEvent.getStateChange();
            String stateString = ((state == ItemEvent.SELECTED) ? "Selected" : "Deselected");
            pw.print("Item: " + itemEvent.getItem());
            pw.print(", State: " + stateString);
            ItemSelectable is = itemEvent.getItemSelectable();
            pw.print(", Selected: " + selectedString(is));
            pw.println();
            textArea.append(sw.toString());
        }
    };
    comboBox.addItemListener(itemListener);

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            pw.print("Command: " + actionEvent.getActionCommand());
            ItemSelectable is = (ItemSelectable) actionEvent.getSource();
            pw.print(", Selected: " + selectedString(is));
            pw.println();
            textArea.append(sw.toString());
        }
    };
    comboBox.addActionListener(actionListener);

    frame.setSize(400, 200);
    frame.setVisible(true);
}

From source file:SendMail.java

public static void main(String[] args) {
    try {//from  w w w  .  j  a v  a2  s . c  om
        // 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>]");
    }
}