socket通讯测试程序时遇到的PrintWriter write与println方法的区别

我也是在做socket的C/S测试的时候发现这个问题的(使用write的时候并没有互相进行通信,但是换成println之后就可以了)。

那么就来看看write和println到底有啥区别吧,先看源码:

println(String x):

    /**
     * Prints a String and then terminates the line.  This method behaves as
     * though it invokes <code>{@link #print(String)}</code> and then
     * <code>{@link #println()}</code>.
     *
     * @param x the <code>String</code> value to be printed
     */
    public void println(String x) {
        synchronized (lock) {
            print(x);
            println();
        }
    }

可见,println()方法,在print()之后输出了一个新的一行,再看看print()干了些啥:

    /**
     * Prints a string.  If the argument is <code>null</code> then the string
     * <code>"null"</code> is printed.  Otherwise, the string's characters are
     * converted into bytes according to the platform's default character
     * encoding, and these bytes are written in exactly the manner of the
     * <code>{@link #write(int)}</code> method.
     *
     * @param      s   The <code>String</code> to be printed
     */
    public void print(String s) {
        if (s == null) {
            s = "null";
        }
        write(s);
    }


再看看println()方法里面干了啥:

    /**
     * Terminates the current line by writing the line separator string.  The
     * line separator string is defined by the system property
     * <code>line.separator</code>, and is not necessarily a single newline
     * character (<code>'\n'</code>).
     */
    public void println() {
        newLine();
    }

newLine():

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;
        }
    }


根据println()的javadoc,newLine()方法输出的lineSeperator不一定就是"\n",但是效果一样,都是另起一行。

所以,也不用看write()方法了,println()方法就是write()+另起一行

如果只是区别,如上,欧了。


那么,为什么在我的socket测试里面,一定要用println方法呢?

就请听下回分解吧!啊哈哈


ref:

http://www.cnblogs.com/draem0507/archive/2013/05/07/3065588.html

http://www.oschina.net/question/101123_17855


版权声明:本文为guamiansang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。