encoding - 如何将 Dart 的ByteData转换为字符串?
我正在读取一个二进制文件,并希望将其转换为字符串。如何在Dart中完成?
最佳答案
尝试以下
String getStringFromBytes(ByteData data) { final buffer = data.buffer; var list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); return utf8.decode(list); }
ByteData 是一个抽象:
一个固定长度的随机访问字节序列,它还提供对这些字节表示的固定宽度整数和浮点数的随机和未对齐访问。
正如 Gunter 在评论中提到的,您可以使用File.writeAsBytes. 但是,它确实需要一些 API 工作才能从ByteData到List<int>。
import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; Future<void> writeToFile(ByteData data, String path) { final buffer = data.buffer; return new File(path).writeAsBytes( buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
你需要安装path_provider包,然后
这应该工作:
import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'package:path_provider/path_provider.dart'; final dbBytes = await rootBundle.load('assets/file'); // <= your ByteData //======================= Future<File> writeToFile(ByteData data) async { final buffer = data.buffer; Directory tempDir = await getTemporaryDirectory(); String tempPath = tempDir.path; var filePath = tempPath + '/file_01.tmp'; // file_01.tmp is dump file, can be anything return new File(filePath).writeAsBytes( buffer.asUint8List(data.offsetInBytes, data.lengthInBytes)); } //======================
获取您的文件:
var file; try { file = await writeToFile(dbBytes); // <= returns File } catch(e) { // catch errors here }
如何转换ByteData
为List<int>
?
经过自我调查,解决方案是:
- 用
.cast<int>()
ByteData audioByteData = await rootBundle.load(audioAssetsFullPath); Uint8List audioUint8List = audioByteData.buffer.asUint8List(audioByteData.offsetInBytes, audioByteData.lengthInBytes); List<int> audioListInt = audioUint8List.cast<int>();
或 2. 使用 .map
ByteData audioByteData = await rootBundle.load(audioAssetsFullPath); Uint8List audioUint8List = audioByteData.buffer.asUint8List(audioByteData.offsetInBytes, audioByteData.lengthInBytes); List<int> audioListInt = audioUint8List.map((eachUint8) => eachUint8.toInt()).toList();