Reputation: 23
When i try to this in Android Studio it ignores the encoding resulting a disaster in my program.But it does not have any problem when i try this on java.
System.setProperty("file.encoding","ISO-8859-1");
Field charset = Charset.class.getDeclaredField("defaultCharset");
charset.setAccessible(true);
charset.set(null,null);
on the log it displays:
E/System: Ignoring attempt to set property "file.encoding" to value "ISO-8859-1"
Upvotes: 2
Views: 609
Reputation: 5459
Setting a system property can be prevented by a SecurityManager if one is installed. An Android application can be expected to run in a sandbox which means that there is a SecurityManager in place that resticts the system properties you can set (there might be some but don't count on it).
A regular Java application in general runs without a SecurityManager so setting this property works.
Normally setting the file.encoding during runtime isn't necessary. If your application breaks without a specific value for file.encoding
you most likely do something wrong within your code, e.g. creating a String
froma byte[]
without specifying the charset to be used or vice versa.
In short: In order to get your application to work you need to change your application from e.g.
byte[] myBytes = myString.getBytes();
String mynewString = new String(myBytes);
InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
to
byte[] myBytes = myString.getBytes("8859_1");
String mynewString = new String(myBytes, "8859_1");
InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "8859_1");
Oh and something more:
Field charset = Charset.class.getDeclaredField("defaultCharset");
charset.setAccessible(true);
charset.set(null,null);
This is quite a hack and you should feel dirty for that ;-) This won't solve all problem, e.g. when you do HTTP-requests, file.encoding
is used as well to decide what charset should be used to encode HTTP-request-header-values. The charset value for that is kept in a different member of a different class, same for similar functionalities in JavaMail, etc. Changing the charset-values in members of "internal" classes is quite likely breaking things, so don't do that and as I already wrote, it should be completely unnecessary.
Upvotes: 1