What is the difference between append and write methods of java.io.writer?

人走茶凉 提交于 2019-12-03 10:38:13

问题


The java.io.Writer interface has two methods called append and write. What are the differences between these two? It even says that

An invocation of this method of the form out.append(c) behaves in exactly the same way as the invocation out.write(c)

so what is the reason for having two method name variants?


回答1:


There are minor differences between append() and write(). All of which you can work out by reading the Javadocs. Hint. ;)

  • write will only take a String which must not be null and returns void
  • append will take any CharSequence which can be null and return the Writer so it can be chained.

write is an older style format created before CharSequence was available.

These methods are overloaded so that there is a

  • write(int) where the int is cast to a char. append(char) must be a char type.
  • write(char[] chars) takes an array of char, there is no equivalent append().



回答2:


Probably to conform to the Appendable interface: http://download.oracle.com/javase/6/docs/api/java/lang/Appendable.html




回答3:


Append() can take a CharSequence, whereas write() takes a String.

Since String is an implementation of CharSequence, you can also pass a String to append(). But you can also pass a StringBuilder or StringBuffer to append, which you can't do with write().




回答4:


As you can see from the documentation, append also returns the Writer you have just written to so that you can perform multiple appends such as:

out.append(a).append(b).append(c)



回答5:


Looks to me like it's a byproduct of the Appendable interface which java.io.Writer implements in order to provide compatibility with java.util.Formatter. As you noted, the documentation points out that for java.io.Writer there is no practical difference between the two methods.




回答6:


Writer.append(c) returns the Writer instance. Thus you can chain multiple calls to append, e.g. out.append("Hello").append("World");



来源:https://stackoverflow.com/questions/5949926/what-is-the-difference-between-append-and-write-methods-of-java-io-writer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!