encoding - 如何将 Dart 的ByteData转换为字符串?
【摘要】
encoding - 如何将 Dart 的ByteData转换为字符串?
我正在读取一个二进制文件,并希望将其转换为字符串。如何在Dart中完成?
最佳答案
尝试以下
String getStri...
encoding - 如何将 Dart 的ByteData转换为字符串?
我正在读取一个二进制文件,并希望将其转换为字符串。如何在Dart中完成?
最佳答案
尝试以下
String getStringFromBytes(ByteData data) {
final buffer = data.buffer;
var list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
return utf8.decode(list);
}
- 1
- 2
- 3
- 4
- 5
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));
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
你需要安装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));
}
//======================
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
获取您的文件:
var file;
try {
file = await writeToFile(dbBytes); // <= returns File
} catch(e) {
// catch errors here
}
- 1
- 2
- 3
- 4
- 5
- 6
如何转换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>();
- 1
- 2
- 3
或 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();
- 1
- 2
- 3
文章来源: jianguo.blog.csdn.net,作者:坚果前端の博客,版权归原作者所有,如需转载,请联系作者。
原文链接:jianguo.blog.csdn.net/article/details/120006379
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)