What is the exact difference between out.write() and out.print()

后端 未结 9 609
情深已故
情深已故 2020-12-13 20:49

In my servlet I gave both out.print and out.write. but both prints in the browser.

What is the exact difference between these two and when

相关标签:
9条回答
  • 2020-12-13 21:38

    First thing is you can't use javax.​servlet.​jsp.​JspWriter out in a servlet. It has to be used in a .jsp file, because out is a method local variable in _jspService(...) method of your .jsp file.

    There is no difference in the purpose of using out.print() and out.write(). Both are used to write the String version of the given object to JspWriter's buffer.

    However, JspWriter.print() is capable of taking many types of arguments than Writer.write().

    JspWriter.print()

    • Object
    • String
    • boolean
    • char
    • char[]
    • double
    • float
    • int
    • long

    Writer.write()

    • String
    • char
    • int
    0 讨论(0)
  • 2020-12-13 21:44

    PrintWriter's implementation communicates the difference better than javadoc

    public void print(String s) {
        if (s == null) {
            s = "null";
        }
        write(s);
    }
    
    0 讨论(0)
  • 2020-12-13 21:46

    PrintWriter:

    public void write(String s)

    Write a string. This method cannot be inherited from the Writer class because it must suppress I/O exceptions.

    print method has higher level of abstraction.

    public void print(String s)

    Print a string. If the argument is null then the string "null" 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 write(int) method.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题