Wouter Vandenputte
Wouter Vandenputte

Reputation: 2113

Dart/Flutter UTF-16 encoding

I need to read in a file that's been saved in Java Android Studio with this code

fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(json);
os.close();
fos.close();

It turns out that Java uses internally UTF-16 for encoding the characters. I now need to read this files in Flutter SDK (with the Dart language)

file.readAsString(encoding: Latin1).then((str) => {
       print(str)
     }).catchError( (e) => {
       print(e)
});

However, the Latin1 encoding doesn't work perfectly. So I want to read it in using UTF-16 but it seems that Dart does simply not have this functionality, or at least not that I can find.

Utf8Codec does exist but there's not Utf16Codec nor Encoding.getByName("UTF-16"). Utf8 is by the way giving exceptions so this is also no option.

So how can I still read in files in Dart which have been saved in Android Studio Java using UTF-16?

Upvotes: 0

Views: 10099

Answers (3)

Adam Ghaffarian
Adam Ghaffarian

Reputation: 61

  final File file = File(filePath);

  final bytes = file.readAsBytesSync();

  final utf16CodeUnits = bytes.buffer.asUint16List();

  final s = String.fromCharCodes(utf16CodeUnits);

I was able to turn a UTF-16 file into a String using these 4 lines to avoid using the discontinued package. Hope this helps!

Upvotes: 1

M.ArslanKhan
M.ArslanKhan

Reputation: 3918

Use Base64. Importing 'dart:convert'.

  var bytes = await file.readAsBytes();
  final encoded = base64.encode(bytes);
  debugPrint("onPressed " + encoded);

Upvotes: -4

Richard Heap
Richard Heap

Reputation: 51770

Use the utf package.

  var bytes = await file.readAsBytes();
  var decoder = Utf16BytesToCodeUnitsDecoder(bytes); // use le variant if no BOM
  var string = String.fromCharCodes(decoder.decodeRest());

Upvotes: 4

Related Questions