androidapache-commons

java.io.UnsupportedEncodingException: java.nio.charset.CharsetICU[UTF-8]


android studio 3.6

in build.gradle:

compileOptions {
        targetCompatibility JavaVersion.VERSION_1_8
        sourceCompatibility JavaVersion.VERSION_1_8
    }

api 'org.apache.commons:commons-io:1.3.2'

in my code

import org.apache.commons.io.FileUtils
import java.io.*
import java.nio.charset.StandardCharsets

     val file = File(folderPath + File.separator + resultFileName)
                FileUtils.writeStringToFile(
                    file,
                    fileContents,
                    StandardCharsets.UTF_8.toString()
                )

but I get error:

 java.nio.charset.CharsetICU[UTF-8]
 java.io.UnsupportedEncodingException: java.nio.charset.CharsetICU[UTF-8]
    at java.nio.charset.Charset.forNameUEE(Charset.java:322)
    at java.lang.String.getBytes(String.java:534)
    at org.apache.commons.io.IOUtils.write(IOUtils.java:810)
    at org.apache.commons.io.FileUtils.writeStringToFile(FileUtils.java:1110)
    at com.myproject.client.common.util.AndroidFileUtil.saveTextToFile(AndroidFileUtil.kt:106)
    at com.myproject.client.service.RecognizedCheckDataService$Companion.saveRecognizedText(RecognizedCheckDataService.kt:117)
    at com.myproject.client.viewmodel.ScanCheckRompetrolViewModel.finishProcessRecognizedCheck(ScanCheckRompetrolViewModel.kt:1059)
    at com.myproject.client.viewmodel.ScanCheckRompetrolViewModel.access$finishProcessRecognizedCheck(ScanCheckRompetrolViewModel.kt:28)
    at com.myproject.client.viewmodel.ScanCheckRompetrolViewModel$runDetector$1.onSuccess(ScanCheckRompetrolViewModel.kt:193)
    at com.myproject.client.viewmodel.ScanCheckRompetrolViewModel$runDetector$1.onSuccess(ScanCheckRompetrolViewModel.kt:28)
    at com.google.android.gms.tasks.zzn.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.nio.charset.IllegalCharsetNameException: java.nio.charset.CharsetICU[UTF-8]

Solution

  • Charset#toString() is not well specified; on Android, it returns "java.nio.charset.CharsetICU[UTF-8]" as found here. And that string is of course not the name of an existing charset.

    But there is no need for the toString() call at all. The writeStringToFile method has an overload that accepts a Charset directly.