当前位置:网站首页>Dart series: smooth as silk, operating files and directories
Dart series: smooth as silk, operating files and directories
2022-06-23 22:05:00 【Procedural stuff】
brief introduction
File operation is IO A very common operation in , So it corresponds to dart language , Is it easy to operate files ? actually dart Provides two ways to read files , One is to read all at once , One is to read the file as a stream .
The disadvantage of one-time reading is that you need to load all the file contents into memory at one time , If the file is large , It's going to be awkward . So we also need the way of streaming reading files . Let's see dart How to read these two files in .
File
in fact dart There are many places in File This class , Here we are going to explain File Class is dart:io In bag .
Read entire file
File A document representing a whole , He has three constructors , Namely :
factory File(String path) factory File.fromUri(Uri uri) factory File.fromRawPath(Uint8List rawPath)
One of the most commonly used is the first constructor .
We can construct a file like this :
var file = File('file.txt');With the files , You can call File Various reading methods in .
There are two forms of file reading itself , One is text , One is binary .
If it's a text file ,File Provides readAsString Methods , Read the entire file as a string .
Future<String> readAsString({Encoding encoding: utf8});We can use :
var stringContents = await file.readAsString();
in addition , We can also read the file line by line :
Future<List<String>> readAsLines({Encoding encoding: utf8});The result is a List,list Represents the contents of each line of the file .
var lines = await file.readAsLines();
The above two methods are asynchronous methods ,File Two synchronization methods are also provided :
String readAsStringSync({Encoding encoding: utf8});
List<String> readAsLinesSync({Encoding encoding: utf8});If the file is binary , Then you can use readAsBytes Or synchronization method readAsBytesSync:
Future<Uint8List> readAsBytes(); Uint8List readAsBytesSync();
dart There is a special type of binary representation called Uint8List, What he actually means is int Of List.
Or just the file , Let's see how to read in binary form :
var file = File('file.txt');
var contents = await file.readAsBytes();Read the file as a stream
The reading method we mentioned above , All read the whole file at once , The disadvantage is that if the file is too large , May cause pressure on memory space .
therefore File It provides us with another way to read files , Stream to read the file .
The corresponding definition method is as follows :
Stream<List<int>> openRead([int? start, int? end]);
Let's look at a basic use :
import 'dart:io';
import 'dart:convert';
Future<void> main() async {
var file = File('file.txt');
Stream<List<int>> inputStream = file.openRead();
var lines = utf8.decoder
.bind(inputStream)
.transform(const LineSplitter());
try {
await for (final line in lines) {
print('Got ${line.length} characters from stream');
}
print('file is now closed');
} catch (e) {
print(e);
}
}Random access
In general, files are accessed sequentially , But sometimes we need to skip some of the previous data , Jump directly to the destination address , You need random access to the file .
dart Provides open and openSync Two methods to read and write random files :
Future<RandomAccessFile> open({FileMode mode: FileMode.read});
RandomAccessFile openSync({FileMode mode: FileMode.read});RandomAccessFile Provides random reading and writing methods for files . Very easy to use .
Writing files
Writing is the same as file reading , You can write once or get a write handle , And then write .
There are four ways to write once , Corresponding to string and binary respectively :
Future<File> writeAsBytes(List<int> bytes,
{FileMode mode: FileMode.write, bool flush: false});
void writeAsBytesSync(List<int> bytes,
{FileMode mode: FileMode.write, bool flush: false});
Future<File> writeAsString(String contents,
{FileMode mode: FileMode.write,
Encoding encoding: utf8,
bool flush: false});
void writeAsStringSync(String contents,
{FileMode mode: FileMode.write,
Encoding encoding: utf8,
bool flush: false});Handle form can call openWrite Method , Return to one IOSink object , Then write through this object :
IOSink openWrite({FileMode mode: FileMode.write, Encoding encoding: utf8});var logFile = File('log.txt');
var sink = logFile.openWrite();
sink.write('FILE ACCESSED ${DateTime.now()}\n');
await sink.flush();
await sink.close();By default, writing overwrites the entire file , However, the write mode can be changed in the following ways :
var sink = logFile.openWrite(mode: FileMode.append);
Handling exceptions
although dart All exceptions in are runtime exceptions , But and java equally , To manually handle exceptions in file reading and writing , You can use try,catch:
Future<void> main() async {
var config = File('config.txt');
try {
var contents = await config.readAsString();
print(contents);
} catch (e) {
print(e);
}
}summary
That's all dart The file operation in .
This article has been included in http://www.flydean.com/23-dart-file/
边栏推荐
- Xgboost implements text classification and sklearn NLP library tfidfvectorizer
- ECS (no matter which one, as long as it is an ordinary ECS) uses the installed version of SketchUp to install an error
- 从CVPR 2022看域泛化(Domain Generalization)最新研究进展
- High quality "climbing hand" of course, you have to climb a "high quality" wallpaper
- Cloud database smooth disassembly scheme
- 嵌入式开发:嵌入式基础——重启和重置的区别
- DM sub database and sub table DDL "pessimistic coordination" mode introduction - tidb tool sharing
- TDD development mode recommendation process
- 蓝牙芯片|瑞萨和TI推出新蓝牙芯片,试试伦茨科技ST17H65蓝牙BLE5.2芯片
- How to use zero to build a computer room
猜你喜欢

Polar cycle graph and polar fan graph of high order histogram

发现一个大佬云集的宝藏硕博社群!

微信小程序中发送网络请求

HDLBits-&gt; Circuits-&gt; Arithmetic Circuitd-&gt; 3-bit binary adder

Leetcode must review six lintcode (28348455116385)

Analysis of Alibaba cloud Tianchi competition -- prediction of o2o coupon

实验五 模块、包和库

How to use the serial port assistant in STC ISP?

Simple code and design concept of "back to top"

从CVPR 2022看域泛化(Domain Generalization)最新研究进展
随机推荐
Raid card with hardware knowledge (5)
Relevant logic of transaction code MICn in SAP mm
API gateway verification token the role of adding a new authentication token in API gateway
Unusual transaction code mebv of SAP mm preliminary level
The most common usage scenarios for redis
How to solve the loss of video source during easynvr split screen switching?
Outlook開機自啟+關閉時最小化
MySQL de duplication query only keeps one latest record
北大、加州伯克利大学等联合| Domain-Adaptive Text Classification with Structured Knowledge from Unlabeled Data(基于未标记数据的结构化知识的领域自适应文本分类)
How to write test cases efficiently?
Open source C # WPF control library -newbeecoder UI usage guide (I)
使用 Provider 改造屎一样的代码,代码量降低了2/3!
微信小程序中发送网络请求
Bing 404? Microsoft suspended "search suggestions" in Bing mainland for 30 days
Interpretation of opentelemetry project
万字长文!一文搞懂InheritedWidget 局部刷新机制
智能座舱SoC竞争升级,国产7nm芯片迎来重要突破
Selenium批量查询运动员技术等级
个税怎么算?你知道吗
The "Star" industry in the small town is escorted by wechat cloud hosting