2

In iOS there is a method canBeConvertedToStringEncoding that will tell you if a given string can be encoded to the provided encoding/charset type (i.e. UTF-8, ISOLatin1 etc...). Is there any equivalent built in method available in Android/Java ?

iOS also has a fastestEncoding and smallestEncoding which will return the best encoding type available for the given string. Does Android have any equivalent for these ?

Thanks.

Mudlabs
  • 551
  • 5
  • 16

3 Answers3

1

In the android transcode text like this:

byte[] utf8 = new String(string, "ISO-8859-1").getBytes("UTF-8");

Please refer to How do I convert between ISO-8859-1 and UTF-8 in Java?

Charset canEncode:

boolean ISO = Charset.forName("ISO-8859-1").newEncoder()
                .canEncode(str);

https://developer.android.com/reference/java/nio/charset/Charset.html#canEncode()

lazy
  • 149
  • 8
  • Thanks @lazy, but I'm not looking for _how to encode_. Rather if Android has a method for testing __IF__ a string can be converted to a particular encoding _(like iOS does)_. Otherwise you have to try to encode and catch any error, then try another encoding etc... – Mudlabs Jul 17 '19 at 02:13
  • @Mudlabs ok,I understand what you want. you can use "Charset" – lazy Jul 17 '19 at 02:39
1

Java doesn't have such kind of method, but you can check whether a string can be represented properly in a specific character encoding, by trying encoding/decoding.

For example, you can make your own string.canBeConvertedToStringEncoding equivalent as follows:

import java.io.UnsupportedEncodingException;

class Main {
  public static void main(String[] args) throws UnsupportedEncodingException {
    if (canBeConvertedToStringEncoding("abc", "ISO-8859-1")) {
      System.out.println("can be converted");
    } else {
      System.out.println("cannot be converted");
    }

    if (canBeConvertedToStringEncoding("あいう", "ISO-8859-1")) {
      System.out.println("can be converted");
    } else {
      System.out.println("cannot be converted");
    }
  }

  public static boolean canBeConvertedToStringEncoding(String target, String encoding) throws UnsupportedEncodingException {
    String to = new String(target.getBytes(encoding), encoding);
    return target.equals(to);
  }
}
SATO Yusuke
  • 1,600
  • 15
  • 39
0

Try with URLEncoder.encode(string, "UTF-8");

jkdev
  • 11,360
  • 15
  • 54
  • 77
Nik
  • 1,991
  • 2
  • 13
  • 30