I have an application which creates a csv-file. The file is then imported by an excel makro. The makro needs the file to be encoded with UTF-16LE encoding. The problem is, i am not able to use this encoding on some devices.
Until now, i used the charset UTF-16 to create the file. When i opende the file with notepad++ it showed me the file is encoded in UTF-16LE. Now I have a new device and when i create the csv-file with it, notepad++ shows me the encoding is UTF-16BE. As a result, i get an error when i try to import the file with the excel makro.
I tried to specify the encoding as UTF-16LE which should be a valid charset according to the developer page of android. But then notepad++ doesn't recognise the encoding of my file and the excel makro is not able to read it (For the old and the new device).
I am able to convert the encoding in both cases via notepad++ to UTF-16LE and successfully import the file with my makro, but I need to create the file from my app in the correct format.
The older device has android version 5.1
The newer device has android version 9.0
Here is my code:
File file = new File("some_name");
if (file.exists()) {
file.delete();
}
file.getParentFile().mkdirs();
file.createNewFile();
Writer osw = new OutputStreamWriter(new FileOutputStream(file),"UTF-16LE"); //Or "UTF-16"
osw.write("foo");
osw.write("bar");
osw.close();
How can i use UTF-16LE encoding on the new device?
I did take a look at this answere and implemented it like this:
Writer osw = new OutputStreamWriter(new FileOutputStream(file),"UTF-16LE"); //Or "UTF-16"
osw.write(new String(("foo").getBytes("UTF-16LE"), "UTF-16LE"));
osw.write(new String(("bar").getBytes("UTF-16LE"), "UTF-16LE"));
osw.close();
I also used the StandardCharsets.UTF_16LE but it didn't change anything. The encoding does still not get recognized by notepad++ and doesn't get imported by the makro.
You can try to explicitly force UTF-16LE encoding with a byte order mark (bom) that specifies the encoding. Notepad++ as well as Excel can interpret the bom. As an example, the following code will produce a csv file suitable for import into Excel using a byte order mark:
The resulting file produced on an Android 9 emulator looks like this:
Notepad++ interprets the file like this:
And Excel displays the following after importing the file:
This doesn't answer your question directly, but you should be able to use this code with your data to help diagnose the problem.
I left this in a comment, but I will mention it again here: The UTF decoder behavior did change with Android 9 to become more compliant with Unicode standards. Those changes are described here. Not sure what effect, if any, this would have in your situation, but it is worth taking a look at (IMO).