Java basics: printwriter

Source: Internet
Author: User

Before reading this blog, I hope you know the Java Io technology and have at least written the demo of Io operations!

We recommend that you check the flush method in the Java IO: Io stream.

This blog mainly uses Socket instances (a simple small example) to solve the problem, and then explores the problem.

1. socket server

package mark.zhang;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;public class Server {public static void main(String[] args) throws Exception {ServerSocket server = new ServerSocket(3000);Socket socket = server.accept();InputStream is = socket.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));String info = br.readLine();System.out.println("server receive info: " + info);}}

2. Socket Client

package mark.zhang;import java.io.OutputStream;import java.io.PrintWriter;import java.net.Socket;public class Client {public static void main(String[] args) throws Exception {Socket client = new Socket("127.0.0.1", 3000);OutputStream os = client.getOutputStream();PrintWriter pw = new PrintWriter(os, true);pw.print("Hello,Server");pw.close();// pw.println("Hello,Server");}}

The code is very simple, mainly because the client sends a string to the server and the server prints the received information.

After the above Code is run (server. Java is run first and client. Java is run), everything is normal!

After debugging, I found that the call level:

Printwriter's close () method ---> bufferedwriter's close () method ---> outputstreamwriter's close () method ---> streamencoder's close () method

Bufferedwriter's close () method source code:

public void close() throws IOException {synchronized (lock) {    if (out == null) {return;    }    try {        flushBuffer();    } finally {        out.close();        out = null;        cb = null;    }}

Source code of the close () method of outputstreamwriter:

public void close() throws IOException {se.close();}

For the source code of the close () method of streamencoder, see the code in this article http://blog.csdn.net/android+th/article/details/6460.pdf.

So, let's make some adjustments to change these normal responses! Modify the client code (comment out PW. Close ()):

package mark.zhang;import java.io.OutputStream;import java.io.PrintWriter;import java.net.Socket;public class Client {public static void main(String[] args) throws Exception {Socket client = new Socket("127.0.0.1", 3000);OutputStream os = client.getOutputStream();PrintWriter pw = new PrintWriter(os, true);pw.print("Hello,Server");// pw.close();// pw.println("Hello,Server");}}

Result printed by the server:

server receive info: null

That is, no information is received. That is to say, this method cannot receive information on the server.

After a prank, we modify the code again as follows:

package mark.zhang;import java.io.OutputStream;import java.io.PrintWriter;import java.net.Socket;public class Client {public static void main(String[] args) throws Exception {Socket client = new Socket("127.0.0.1", 3000);OutputStream os = client.getOutputStream();PrintWriter pw = new PrintWriter(os, true);//pw.print("Hello,Server");//pw.close();pw.println("Hello,Server");}}

OK. The server can receive the information. Let's look at the source code of the println method of the printwriter class:

public void println(String x) {synchronized (lock) {    print(x);    println();}
public void print(String s) {if (s == null) {    s = "null";}write(s);}
public void println() {newLine();}

Newline () is to add a carriage return:

private void newLine() {try {    synchronized (lock) {ensureOpen();out.write(lineSeparator);if (autoFlush)    out.flush();    }}catch (InterruptedIOException x) {    Thread.currentThread().interrupt();}catch (IOException x) {    trouble = true;}    }

Lineseparator definition:

lineSeparator = (String) java.security.AccessController.doPrivileged(               new sun.security.action.GetPropertyAction("line.separator"));

The Readline () method of the server, when a carriage return reads data once (one row ). Therefore, the server can receive information.

3. Study Readline

Modify the client. Java code again:

package mark.zhang;import java.io.DataOutputStream;import java.io.OutputStream;import java.net.Socket;public class Client {public static void main(String[] args) throws Exception {Socket client = new Socket("127.0.0.1", 3000);OutputStream os = client.getOutputStream();DataOutputStream dos = new DataOutputStream(os);dos.writeBytes("Hello,Server1");dos.writeBytes("\n");dos.writeBytes("Hello,Server2");//dos.close();}}

Server receiving information:

server receive info: Hello,Server1

Note: No hello, server2 is received. This indicates that if Readline encounters a carriage return, the system reads the information.

For other usage of the Readline () method, see the following code:

Package csdn. zhwx; import Java. io. bufferedreader; import Java. io. bufferedwriter; import Java. io. file; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. outputstreamwriter; import Java. NIO. charset. charset; public class bufferedreadertest {public static void GetFile (string readfilepath, string readfilename, string writef Ilepath, string writefilename) {file reafile = NULL; fileinputstream FCM = NULL; bufferedreader breader = NULL; file writefile = NULL; fileoutputstream Fos = NULL; bufferedwriter bwriter = NULL; try {If (! (Readfilename = NULL | readfilename. length () <= 0) {reafile = new file (readfilepath + readfilename); FCM = new fileinputstream (reafile); // breader = new bufferedreader (New inputstreamreader (FCM, "GBK"); // specifies the GBK encoding, which is generally used in Chinese Windows. // Breader = new bufferedreader (New inputstreamreader (FCM); // default encoding, consistent with the system encoding. Linux is UTF-8bReader = new bufferedreader (New inputstreamreader (FCM, "UTF-8"); // specifies the UTF-8 encoding writefile = new file (writefilepath, writefilename ); fos = new fileoutputstream (writefile); // bwriter = new bufferedwriter (New outputstreamwriter (FOS); // default encoding, consistent with the system encoding. Linux is UTF-8bWriter = new bufferedwriter (New outputstreamwriter (FOS, "UTF-8"); // specifies the UTF-8 encoding string STR = NULL; while (STR = breader. Readline ())! = NULL) {// This method does not write the newline \ n read to the file. // system. out. println (STR); // manually add \ nbwriter. write (STR + "\ n");/* bwriter. write (STR); bwriter. newline (); * // if it is not refreshed, the file will not contain bwriter. flush () ;}} catch (exception e) {e. printstacktrace (); try {FCM. close (); breader. close (); FOS. close (); bwriter. close () ;}catch (ioexception E1) {e1.printstacktrace () ;}} finally {try {FCM. close (); breader. close (); FOS. close (); bwriter. close () ;}catch (ioexception E1) {e1.printstacktrace () ;}} public static void main (string [] ARGs) {GetFile ("/home/Zhihui/downloads/", "hello.txt", "/home/Zhihui/downloads/", "copyformhello.txt "); // Linux test/* Current JRE: 1.6.0 _ 23 current default JVM Character Set: UTF-8 */system. out. println ("Current JRE:" + system. getproperty ("Java. version "); system. out. println ("Default JVM Character Set:" + charset. defaultcharset ());}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.