Write text to file in Flutter(Dart) - flutter

I want to be able to create a new file and write a string into it. Examples that I can find all seems to pertain to writing to an existing file.
String fileName = 'myFile.txt';
String contents = 'hello';
void writeToFile(String fileName, String contents){
File outFile = File('content://com.android.providers.media.documents/document/document/document_root/' + fileName);
outFile.writeAsString(contents);
}
This results in the following error, as expected
Unhandled Exception: FileSystemException: Cannot open file, path = 'content://com.android.providers.media.documents/document/document/document_root/myFile.txt' (OS Error: No such file or directory, errno = 2)
How can I create a new file in which I can write my contents?

Are you sure that the path exists? writeAsString does create the file if it doesn't exists, but it doesn't create the full folder structure up to the file you're trying to write to. Also, you might not have the rights to write in the path you've specified.
Anyway, you'd better use this plugin to get the folders' path instead of hard-coding them.

Related

flutter: how to create/write a file to a specific directory path

i'm trying to create/write a file to a specific directory. i already have my code but the problem is i always got an error saying:
flutter: FileSystemException: Cannot open file, path = '/var/mobile/Containers/Data/Application/AF14244D-E8C4-4B9A-8005-D7CA7CC3520B/Documents/cache/files/abcb-1234567890' (OS Error: No such file or directory, errno = 2)
here's my code:
Directory directory = Platform.isAndroid ? await getExternalStorageDirectory() : await getApplicationDocumentsDirectory();
String path = directory.path + '/cache/files';
File file = new File('$path/$fileID');
final results = await post(...);
file.writeAsBytesSync(results);
what am i missing?
additional question: if anyone would know how can i access created date of the file that i have just created? - reason for this is to delete them after a set date or like an expiry date.
appreciate any help. thank you in advance. =)
Are you sure this path exists?
I belive your code is executing part getApplicationDocumentsDirectory()
That mean you are not on android.
Can you access this path using other app (some file explorer etc)?
The interesting part is here:
'/cache/files' maybe this folder doesn't exist.
Here is on my Windows:
var dir = io.Directory.fromUri(Uri.directory('UNO\\DUE\\'));
dir.createSync(recursive: true);
var file = io.File('${dir.absolute.path}\demo.txt');
file.writeAsStringSync('ABCDEFHJ');
Without dir.createSync(recursive: true); without recursive parameter I have exactly same problem.

Read multiple h5 files but there is an os error couldn't find these files

When I am trying to read many h5 files in one shoot. There is an OS error states like this:
OSError: Unable to open file (unable to open file: name = '/scratch-lustre/hpc-0227/deepcpgData/c{1,2,3,4,5,7,9,11,13}_*.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)
I am sure all of these files exist and files' name corresponded with c{1,2,3,4,5,7,9,11,13}_*.h5 rightly. I am also using absolute path. My bash script looks like this:
data_dir="/scratch-lustre/hpc-0227/deepcpgData"
train_files="$data_dir/c{1,2,3,4,5,7,9,11,13}_*.h5"
It works when I use the full name of a single file, for example, c16_1572864-1605632.h5. However, I need to read a lot of files. So I have to read them in one round. I have searched many other answers but none of them deal with multiple files and the os error at the same time.

Batch Printing files to new folder as PDF's

I have a folder of 2000+ PDF files that I need to print and resave as new PDF files in a separate folder using the original file name. Is there a way to do this in powershell or using a CMD?
I have tried to select multiple files in the folder to print at the same time by right clicking and selecting the print option. However this gets stuck at the window requesting a new file name and a destination folder which I am unable to provide as each file needs to have the original file name.
// the directory to store the output.
string directory = Environment.GetFolderPath
(Environment.SpecialFolder.MyDocuments);
// initialize PrintDocument object
PrintDocument doc = new PrintDocument() {
PrinterSettings = new PrinterSettings() {
// set the printer to 'Microsoft Print to PDF'
PrinterName = "Microsoft Print to PDF",
// tell the object this document will print to file
PrintToFile = true,
// set the filename to whatever you like (full path)
PrintFileName = Path.Combine(directory, file + ".pdf"),
}
};
doc.Print();
I would like to see the new PDF file saved as a new PDF in the destination directory folder with the same file name as the origin directory.
Origin Directory and File name:
C:\Users\ts\P***S***\Legal\i3**\NonRedacted --> Origin File name "Random_Name.PDF"
Destination Directory and File name:
C:\Users\ts\P***S***\Legal\i3**\Redacted --> Destination File Name "Random_Name.PDF"

Specman e error: No match for file when using "for each line in file"

I have a my_text.txt file and the next e file in the same directory:
extend my_unit {
run() is also {
for each line in file "my_text.txt" do {
// ...
};
};
};
I get the next run error:
*** Error: No match for file 'my_text.txt'
Why do I get the error? How the for loop over all lines in a text file should be used?
Thank you for your help
The file name is looked for relatively to your working directory (from which you run Specman), not relatively to the source file in which the code is written.
It does consider SPECMAN_PATH, but probably your SPECMAN_PATH does not point directly to that directory.

How to do File creation and manipulation in functional style?

I need to write a program where I run a set of instructions and create a file in a directory. Once the file is created, when the same code block is run again, it should not run the same set of instructions since it has already been executed before, here the file is used as a guard.
var Directory: String = "Dir1"
var dir: File = new File("Directory");
dir.mkdir();
var FileName: String = Directory + File.separator + "samplefile" + ".log"
val FileObj: File = new File(FileName)
if(!FileObj.exists())
// blahblah
else
{
// set of instructions to create the file
}
When the programs runs initially, the file won't be present, so it should run the set of instructions in else and also create the file, and after the first run, the second run it should exit since the file exists.
The problem is that I do not understand new File, and when the file is created? Should I use file.CreateNewFile? Also, how to write this in functional style using case?
It's important to understand that a java.io.File is not a physical file on the file system, but a representation of a pathname -- per the javadoc: "An abstract representation of file and directory pathnames". So new File(...) has nothing to do with creating an actual file - you are just defining a pathname, which may or may not correspond to an existing file.
To create an empty file, you can use:
val file = new File("filepath/filename")
file.createNewFile();
If running on JRE 7 or higher, you can use the new java.nio.file API:
val path = Paths.get("filepath/filename")
Files.createFile(path)
If you're not happy with the default IO APIs, you an consider a number of alternative. Scala-specific ones that I know of are:
scala-io
rapture.io
Or you can use libraries from the Java world, such as Google Guava or Apache Commons IO.
Edit: One thing I did not consider initially: I understood "creating a file" as "creating an empty file"; but if you intend to write something immediately in the file, you generally don't need to create an empty file first.