简体   繁体   中英

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

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?

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().

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() .

正如您从文档中看到的那样,append还会返回您刚刚编写的Writer,以便您可以执行多个附加,例如:

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

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

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.

What has been noted above is true. The different flavours of BufferWiter 's append() method return a Writer , which implements Appendable , among others, thereby affording you the ability to chain calls. In addition, append() allows you to pass a CharSequence as well as a char , as opposed to an int , String or char[] , as with the write() methods. All correct.

However, as the question states, an important issue to point out that the underlying behaviour of append() is still much the same as that of write() . Despite the somewhat misleading nomenclature, existing file content will be overwritten, not appended , unless your FileWriter is instantiated otherwise:

try (var writer = new BufferedWriter(new FileWriter("myFile.txt", true));) {
    writer.append("XXX").append("ZZZ");
}

In that sense I think the original question raises a valid point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM