In this post, we will learn “How to write String to a file in Java 11?”. Java 11 introduced writeString() API to do that.

Here, we are going to learn following things:

  1. What is writeString() API?
  2. How to use it?

Write String to a File in Java 11 using writeString method?...!!! Click To Tweet

Let’s Begin,

1. What is writeString() API?

Java 11 introduced two new overloaded methods as part of java.nio.file.Files class. 

Path writeString​(Path path, CharSequence csq, OpenOption… options):

  • This method write a CharSequence to a file. Characters are encoded into bytes using the UTF-8 charset.
  • This method is equivalent to: writeString(path, test, StandardCharsets.UTF_8, options)

writeString1_Java11_Signature_Techndeck

Path writeString​(Path path, CharSequence csq, Charset cs, OpenOption… options): 

  • This method write a CharSequence to a file. Characters are encoded into bytes using the specified charset.
  • All characters are written as they are, including the line separators in the char sequence. No extra characters are added.
  • The options parameter specifies how the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn’t exist, or initially truncating an existing regular-file to a size of 0.

writeString2_Java11_Signature_Techndeck

2. How to use it?

Let’s take an example where we have a File (TestingFile.txt). Now, we are going to write some string content onto that File using writeString API.

Note: In below example, after writing into the file, we are performing a check to make sure string is successfully written onto the file.

Output:

Write String to a File in Java 11 using writeString method?...!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References: