#capacitor/filesystem: How to check if a folder/directory exists or not? - capacitor

In my ionic capacitor app, I need to check if a folder exists or not on my device. But I have not found any method in the FileSystem plugin. Although there is a method for reading all the contents inside a directory.
In my case, at first, I need to check if the directory already exists or not. If it is not found, then I will create the directory.

In try block write the code for creating a directory. An exception will be thrown otherwise.
try {
let ret = await Filesystem.mkdir({
path: folderName,
directory: FilesystemDirectory.Documents,
recursive: false,
});
console.log("folder ", ret);
} catch (e) {
//console.error("Unable to make directory", e);
}

Related

Flutter: moving files from local machine

Can you use flutter to move files from local machine? For example from C:\images\photo.png to C:\photos\photo.png?
Yes you can make files moving using Dart/Flutter, you need to import dart:io :
import "dart:io";
then you can use this method, you can understand what it does with the comments I wrote.
Future<File> moveFile(File originalFile, String targetPath) async {
try {
// This will try first to just rename the file if they are on the same directory,
return await originalFile.rename(targetPath);
} on FileSystemException catch (e) {
// if the rename method fails, it will copy the original file to the new directory and then delete the original file
final newFileInTargetPath = await originalFile.copy(targetPath);
await originalFile.delete();
return newFileInTargetPath;
}
}
final file = File("C:/images/photo.png");
final path = "C:/photos/";
await moveFile(file, path);
However, I will explain here what it does :
If your file is under the same path directory, then there is no need to move it, just rename them with the rename() method will work, if the file is in an else directory on your system, it will create a new File where it will copy that file to that path, Now we will have two copies of that File, one under the old path and the other under the new path, so we need to delete the old one with the delete() method, finally we returned the new file with return newFile;

FileSystemException: Cannot open file, path = 'storage/emulated/0/DCIM/docs/myPdf.pdf' (OS Error: Operation not permitted, errno = 1)

I am trying to create a pdf document and write my data in that file. The data is a list of int or uint type. Able to do the same for images but not pdf or doc file. All permissions are given and it works for images. My code is below -
Future <File> createDocFile(Uint8List fileData, String type) async
{
File file = new File(".pdf");
if(await PermissionHandler.checkPermission(Permission.storage)!=true){
Url.toastShow("Storage permission not found.");
await Permission.storage.request();
}
else {
await file.writeAsBytes(fileData);
print("PDF SAVED IN DEVICE");
Url.toastShow("PDF saved in device",Colors.green);
}
}
Whenever you create a new file the device can't automatically find it. You'd have to manually tell the device to refresh for the files. Before you'd have to refresh all the files in the device for it to get updated which was very inefficient, but now you could just send the path of the file that you want to get updated. You can use the media_scanner plugin to do so.
Or If you wanna do it yourself with kotlin then here's the code,
private fun broadcastFileUpdate(path: String){
context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(File(path))))
}

Flutter create a file and write its contents

I am working on an app which gathers text content from server and as the next step I am trying to save them into separate files to be saved with in apps storage. Storage is a folder called 'storage'. Inside storage, there is a 'fileList.txt' file which contains the list of files.
In pubspec.yaml I declared this folder in the assets as follows:
assets:
- storage/
And I can read it using the following function:
Future<String> readFileContent() async {
String response;
response =
await rootBundle.loadString('storage/fileList.txt');
return response;
}
To save the file I made use of online examples which use 'path_provider' package. However when I try to save one of the downloaded files for instance 'file4.dat' using the following functions, I encounter the following error. How can I resolve that problem?
saveFileLocally() async {
await _writeFile();
}
Future<Null> _writeFile() async {
await (await _getLocalFile()).writeAsString(vars.fileContents);
}
Future<File> _getLocalFile() async {
// get the path to the document directory.
String dir = (await PathProvider.getApplicationSupportDirectory()).path;
print('DIR :::: ' + dir);
return new File(
'$dir/storage/files/file' + vars.newFileID.toString() + '.dat');
}
The error is:
Unhandled Exception: FileSystemException: Cannot open file,
path = '/data/user/0/com.example.ferenova_flutter_app/files/storage/file4.dat'
(OS Error: No such file or directory, errno = 2)
Thanks guys and take care !!! :)
While checking out path_provider examples, I ran into this important detail:
Directory directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory(); //FOR iOS
This solved my problem. I am no longer using default rootBundle asset to process any external files.
I think you should check your paths.
storage/fileList.txt is not the same as $dir/storage/files/file' + vars.loadedFileID.toString() + '.dat'
you should try:
response =
await rootBundle.loadString('$dir/storage/files/file' + vars.loadedFileID.toString() + '.dat'');
Or something similar.
GL

VSCode API check if path exists

In a VSCode extension, how can I check if a file path exists without opening or reading the file?
The closest thing I've found are vscode.workspace.fs.Readfile and vscode.workspace.openTextDocument (https://code.visualstudio.com/api/references/vscode-api#FileSystem), but again, I do not want to open or read the file. Is there a way to do this?
Per #realappie's comment on another answer, you can use vscode.workspace.fs.
It doesn't have a method like exists, but you can use .stat() for that. An example from the repo:
try {
await vscode.workspace.fs.stat(jsUri);
vscode.window.showTextDocument(jsUri, { viewColumn: vscode.ViewColumn.Beside });
} catch {
vscode.window.showInformationMessage(`${jsUri.toString(true)} file does *not* exist`);
}
There is no API for that because there is a builtin function:
import * as fs from 'fs'; // In NodeJS: 'const fs = require('fs')'
if (fs.existsSync(path)) {
// File exists in path
}

Can you copy resources from an eclipse project to a UNC path programmatically?

I'm trying to copy resources (IFile) from an eclipse project to another location. The location is a UNC path which I've used before to create IProjects using IProjectDescription. However, when I try to copy the resource using the following code I get a ResourceException:
IResource[] res = project.members();
for (IResource r : res) {
if (r instanceof IFile) {
IFile file = (IFile) r;
file.copy("\\example.com\User\Folder\sj\", true, null);
}
}
The exception goes something like this:
org.eclipse.internal.resources.ResourceException: Resource '/corp.dsd' does not exist.
Anyone have any ideas?
Try using the IFileStore API. http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/filesystem/IFileStore.html
You can use getLocation on your IFile and then obtain the filestore for it.