当前位置:网站首页>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/
边栏推荐
- Introduction to scikit learn machine learning practice
- How to build an API gateway and how to maintain an API gateway?
- ICML2022 | 基于对比学习的离线元强化学习的鲁棒任务表示
- Start /affinity specifies the number of vcpu to run OpenSSL speed to test the performance of a single vcpu
- The transaction code mp83 at the initial level of SAP retail displays a prediction parameter file
- 北大、加州伯克利大學等聯合| Domain-Adaptive Text Classification with Structured Knowledge from Unlabeled Data(基於未標記數據的結構化知識的領域自適應文本分類)
- Go language core 36 lectures (go language practice and application 27) -- learning notes
- Coding website hosting migration Tencent cloud cloud development webify
- Flink practical tutorial: advanced 4-window top n
- How to realize batch generation of serial number QR code
猜你喜欢

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

Acl2022 | MVR: multi view document representation for open domain retrieval

Code implementation of CAD drawing online web measurement tool (measuring distance, area, angle, etc.)

Leetcode algorithm interview sprint sorting algorithm theory (32)

蓝牙芯片|瑞萨和TI推出新蓝牙芯片,试试伦茨科技ST17H65蓝牙BLE5.2芯片

Peking University, University of California Berkeley and others jointly | domain adaptive text classification with structured knowledge from unlabeled data (Domain Adaptive Text Classification Based o

嵌入式开发:嵌入式基础——重启和重置的区别

北大、加州伯克利大学等联合| Domain-Adaptive Text Classification with Structured Knowledge from Unlabeled Data(基于未标记数据的结构化知识的领域自适应文本分类)

大一女生废话编程爆火!懂不懂编程的看完都拴Q了

Error running PyUIC: Cannot start process, the working directory ‘-m PyQt5. uic. pyuic register. ui -o
随机推荐
Ffmpeg for audio and video commands
How to set the life cycle of API gateway
How do I install the API gateway? What should I pay attention to?
How API gateway finds the role of microserver gateway in microservices
ECS (no matter which one, as long as it is an ordinary ECS) uses the installed version of SketchUp to install an error
Digital transformation solution for supply chain platform of mechanical equipment industry
蓝牙芯片|瑞萨和TI推出新蓝牙芯片,试试伦茨科技ST17H65蓝牙BLE5.2芯片
Detailed explanation of logical structure, physical structure and data operation
How to dynamically insert a picture into a QR code
The 11th Blue Bridge Cup
KnowDA: All-in-One Knowledge Mixture Model for Data Augmentation in Few-Shot NLP(KnowDA:用于 Few-Shot NLP 中数据增强的多合一知识混合模型)
高阶柱状图之极环图与极扇图
HDLBits-&gt; Circuits-&gt; Arithmetic Circuitd-&gt; 3-bit binary adder
小程序ssl证书过期是什么原因导致的?小程序ssl证书到期了怎么解决?
How to improve the content quality of short video, these four elements must be achieved
How to build an API gateway and how to maintain an API gateway?
北大、加州伯克利大學等聯合| Domain-Adaptive Text Classification with Structured Knowledge from Unlabeled Data(基於未標記數據的結構化知識的領域自適應文本分類)
北大、加州伯克利大学等联合| Domain-Adaptive Text Classification with Structured Knowledge from Unlabeled Data(基于未标记数据的结构化知识的领域自适应文本分类)
Selenium batch query athletes' technical grades
Outlook开机自启+关闭时最小化