Issue
I’m trying to open and write to a file using Dart’s IO library.
I have this code:
File file = File("text.txt");
RandomAccessFile raf = file.openSync();
raf.writeStringSync("A string!");
Now when doing this I get the following error in the console:
(OS Error: Access is denied., errno = 5)
So file is not opened for writing, and I’m looking here: open method, and can’t figure out how to use open
or openSync
to get RandomAccessFile
I can write to.
It says I need to use write constant to do that but just can’t figure out how?
If I try to create FileMode and add it to open
method as an argument I get an error saying:
Error: Too many positional arguments: 0 allowed, but 1 found.
So open
and openSync
methods can’t take any arguments, how would one use FileMode
, and open
method to open a file that is ready for writing? So I need to get RandomAccessFile
that is in writing mode? And by default its only in read mode? I’m not trying to use writeString
or writeStringSync
, I know those methods exist, but I’m interested in how is this done using open
and openSync
methods that return RandomAccessFile
!
Update:
Solution
You are getting this error:
Error: Too many positional arguments: 0 allowed, but 1 found.
because the openSync method has no positional arguments, but just one named parameter (mode
).
So to fix your code you must add it:
RandomAccessFile raf = file.openSync(mode: FileMode.append); //Or whatever mode you'd to apply
Having said that, there are several other ways to write to a file, most of them listed in the docs:
-
writeString or writeStringSync, I’d suggest these if what you need is just to write once to a file.
-
openWrite, which returns a
Stream
that can be written in order to write to the file.
(All of these methods have a FileMode mode
named parameter)
Answered By – Mattia
Answer Checked By – Candace Johnson (FlutterFixes Volunteer)