0

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:

Matija
  • 2,610
  • 1
  • 18
  • 18
  • If all what you need is write to a file there are examples written in the api docs https://api.dartlang.org/stable/2.2.0/dart-io/File-class.html – Mattia Apr 01 '19 at 10:25
  • Thanks Mattia, I have seen these examples, but I'm going through all methods now as I learn Dart. I can see we could use openWrite method to open file ready for writing, but it returns IOSink, I'm interested to see how to write to a file using open or openSync methods that returns RandomAccessFile. And how to use FileMode class? Also, if I would like to append some text to a file, I would have to use FileMode class as there is no openAppend method as I can see. – Matija Apr 01 '19 at 10:32

1 Answers1

1

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)

Mattia
  • 5,909
  • 3
  • 26
  • 41
  • Thank you one more time Mattia! So its "positional arguments" and "named paramteres" that confused me! Thanks again! – Matija Apr 01 '19 at 12:10