Skip to content
Rajesh R edited this page Jun 16, 2024 · 1 revision

You can supply your own charset too for anything that does a read/write (it assumes java.nio.charset.Charset.defaultCharset() if you don't provide one):

val content: String = file.contentAsString()  // default charset

// custom charset:
import java.nio.charset.Charset
file.contentAsString(charset = Charset.forName("US-ASCII"))

//or simply using implicit conversion from Strings
file.write("hello world", charset = "US-ASCII")

Note: By default, better-files correctly handles BOMs while decoding. If you wish to have the incorrect JDK behaviour, you would need to supply Java's UTF-8 charset e.g.:

file.contentAsString(charset = Charset.forName("UTF-8"))    // Default incorrect JDK behaviour for UTF-8 (see: JDK-4508058)

If you also wish to write BOMs while encoding, you would need to supply it as:

file.write("hello world", charset = UnicodeCharset("UTF-8", writeByteOrderMarkers = true))
Clone this wiki locally