Renaming a file in as3 AIR - how to do it if you have file's native path in a var? - air

The following code is great for renaming a file if you know the file is in applicationStorageDirectory
var sourceFile:File = File.applicationStorageDirectory;
sourceFile = sourceFile.resolvePath("Kalimba.snd");
var destination:File = File.applicationStorageDirectory;
destination = destination.resolvePath("test.snd");
try
{
sourceFile.moveTo(destination, true);
}
catch (error:Error)
{
trace("Error:" + error.message);
}
How do you set the sourceFile if all you have is the file's native path in a string? Like this:
D:\Software\files\testList.db
This throws errors:
sourceFile = sourceFile.resolvePath("D:\Software\files\testList.db");
The idea is I want to rename a file I had previously loaded into a var. I figured I'd extract the native path to a String var, null the File var (so the OS doesn't tell me it can't be renamed while the file is opened in flash), resolve that nativePath as the sourceFile, and use moveTo to rename the file on the hard drive.
Cheers for taking a look.
EDIT:
I've set up a test AIR app with only the following in it:
import flash.events.*;
import flash.filesystem.*;
var original = File.documentsDirectory;
original = original.resolvePath("D:\\Software\\test\\October.db");
var destination:File = File.documentsDirectory;
destination = destination.resolvePath("copy.db");
original.addEventListener(Event.COMPLETE, fileMoveCompleteHandler);
original.addEventListener(IOErrorEvent.IO_ERROR, fileMoveIOErrorEventHandler);
original.moveToAsync(destination);
function fileMoveCompleteHandler(event:Event):void {
trace(event.target); // [object File]
}
function fileMoveIOErrorEventHandler(event:IOErrorEvent):void {
trace("I/O Error.");
}
This fails, as does using D:\Software\test\October.db
I guess what I want to know it - how do you do the resolvePath thing if you already know the full path?

I guess what I want to know it - how do you do the resolvePath thing if you already know the full path?
You don't AFAIK. If your path is actually d:\software\test\october.db you can set a File ref like:
var original:File = new File();
original.nativePath = "d:\software\test\october.db";

Related

Kotlin: How to save file in a directory? Having errors

Having problems with my code, So I am currently trying to create a new directory and also store a text file within that folder I have created, I looked at a couple of examples but it seems like they only focus on a specific thing like how to create a file or a folder but never how to utilise both. How can I achieve this? I keep hitting exception errors when I try doing different methods, thanks!
val newFile : Int = 1
val fileString = "nameData"
//so we are creating variable to store the directory information
val folderDir = File("G:\\Random Projects\\JVM\\database\\Collection 1")
//we use that variable to create a File class which will create a folder called nameData
//this will also be stored in another variable called f
val f = File(folderDir, "nameData")
//this will create the actual folder based on the variable information
f.mkdir()
//creating file
try {
val fo = FileWriter(fileString, true)
fo.write(a)
fo.close()
} catch (ex:Exception) {
println("Something Went Wrong When Creating File!!")
}
The problem is that you probably don't have the whole folder structure created, that's why you usually use the mkdirs (note the s at the end) function. You can then use the writeBytes function to write the content:
val fileString = "nameData"
val folderDir = File("myfolder")
val f = File(folderDir, "nameData")
f.parentFile.mkdirs()
f.writeBytes(fileString.toByteArray())

With Kotlin write to SD-card on Android

I have read a lot of questions and answers, but are not really satisfied and successful
My Problem: write with Kotlin to a sdcard to a specific directory
Working is
var filenamex = "export.csv"
var patt = getExternalFilesDirs(null)
var path = patt[1]
//create fileOut object
var fileOut = File(path, filenamex)
//create a new file
fileOut.createNewFile()
with getExternalFIlesDirs() I get the external storage and the sdcard. With path = patt[1] i get the adress of my sd-card.
this is
"/storage/105E-XXXX/Android/data/com.example.myApp/files"
This works to write data in this directory.
But I would like to write into an other directory, for example
"/sdcard/myApp"
A lot of examples say, this should work, bit it does not.
So I tried to take
"/storage/105E-XXXX/myApp"
Why doesn't it work? Ist the same beginning of storage /storage/105E-XXXX/, so it is MY sd-card.?
As I mentioned, it works on the sd-card, so it is not a problem of write-permission to the sdcard?
Any idea?
(I also failed with FileOutputStream and other things)
Try Out this..
var filenamex = "export.csv"
var path = getExternalStorageDirectory() + "//your desired folder"
var fileOut = File(path, filenamex)
fileOut.createNewFile()

Flutter: Get the filename of a File

I thought this would be pretty straight-forward, but can't seem to get this. I have a File file and it has a path file.path which spits out something like /storage/emulated/0/Android/data/my_app/files/Pictures/ca04f332.png but I can't seem to find anything to get just ca04f332.png.
You can use the basename function from the dart path library:
import 'package:path/path.dart';
File file = new File("/dir1/dir2/file.ext");
String basename = basename(file.path);
# file.ext
File file = new File("/storage/emulated/0/Android/data/my_app/files/Pictures/ca04f332.png");
String fileName = file.path.split('/').last;
print(fileName);
output = ca04f332.png
Since Dart Version 2.6 has been announced and it's available for flutter version 1.12 and higher, You can use extension methods. It will provide a more readable and global solution to this problem.
file_extensions.dart :
import 'dart:io';
extension FileExtention on FileSystemEntity{
String get name {
return this?.path?.split("/")?.last;
}
}
and name getter is added to all the file objects. You can simply just call name on any file.
main() {
File file = new File("/dev/dart/work/hello/app.dart");
print(file.name);
}
Read the document for more information.
Note:
Since extension is a new feature, it's not fully integrated into IDEs yet and it may not be recognized automatically. You have to import your extension manually wherever you need that. Just make sure the extension file is imported:
import 'package:<your_extention_path>/file_extentions.dart';
Direct way:
File file = File('/foo/bar/baz/my_image.jpg');
String fileName = file.path.split(Platform.pathSeparator).last; // my_image.jpg
Using an extension:
1. Create an extension:
extension FileEx on File {
String get name => path.split(Platform.pathSeparator).last;
}
2. Usage:
File file = File('/foo/bar/baz/my_image.jpg');
String fileName = file.name; // my_image.jpg
Easy way to get name or any other file handling operations.I recommend to use this plugin : https://pub.dev/packages/file_support
main() {
String filename= FileSupport().getFileNameWithoutExtension(<File Object>);
}
You cane use extension method No need to use any package
Create Method like this
extension FileNameExtension on File {
String getFileName() {
String fileName = path.split('/').last;
return fileName;
}
}
implement
File file = File("yourpath/example.pdf");
file.getFileName() // result => example.pdf

where are app scripts stored on Google Drive?

I found a useful script long ago and installed it. Now I want to delete it so it's no longer running, but I have no idea where it is stored so I can delete it. And I don't know it's exact filename to search for it. How do I find the script?? it watches a shared folder on Google Drive and emails me when the contents of the folder are changed.
I need to find this script and delete it.... suggestions????
How about something like this? It uses Mime types to find the scripts.
function findGoogleScripts() {
var ssNew = SpreadsheetApp.create("GoogleScriptsOnMyDrive");
SpreadsheetApp.setActiveSpreadsheet(ssNew);
var sheet = ssNew.getSheets()[0];
var files = DriveApp.getFiles();
sheet.appendRow(["File Name", "Mime Type"]);
while (files.hasNext()) {
var mType, theFile;
var tempArray = [];
theFile = files.next();
mType = theFile.getMimeType();
if (mType.equals("application/vnd.google-apps.script")) {
tempArray.push(theFile.getName());
tempArray.push(mType);
sheet.appendRow(tempArray);
}
}
}

Check if a file exists in the project in WinRT

I have a WinRT Metro project which displays images based on a selected item. However, some of the images selected will not exist. What I want to be able to do is trap the case where they don't exist and display an alternative.
Here is my code so far:
internal string GetMyImage(string imageDescription)
{
string myImage = string.Format("Assets/MyImages/{0}.jpg", imageDescription.Replace(" ", ""));
// Need to check here if the above asset actually exists
return myImage;
}
Example calls:
GetMyImage("First Picture");
GetMyImage("Second Picture");
So Assets/MyImages/SecondPicture.jpg exists, but Assets/MyImages/FirstPicture.jpg does not.
At first I thought of using the WinRT equivalent of File.Exists(), but there doesn't appear to be one. Without having to go to the extent of trying to open the file and catching an error, can I simply check if either the file exists, or the file exists in the project?
You could use GetFilesAsync from here to enumerate the existing files. This seems to make sense considering you have multiple files which might not exist.
Gets a list of all files in the current folder and its sub-folders. Files are filtered and sorted based on the specified CommonFileQuery.
var folder = await StorageFolder.GetFolderFromPathAsync("Assets/MyImages/");
var files = await folder.GetFilesAsync(CommonFileQuery.OrderByName);
var file = files.FirstOrDefault(x => x.Name == "fileName");
if (file != null)
{
//do stuff
}
Edit:
As #Filip Skakun pointed out, the resource manager has a resource mapping on which you can call ContainsKey which has the benefit of checking for qualified resources as well (i.e. localized, scaled etc).
Edit 2:
Windows 8.1 introduced a new method for getting files and folders:
var result = await ApplicationData.Current.LocalFolder.TryGetItemAsync("fileName") as IStorageFile;
if (result != null)
//file exists
else
//file doesn't exist
There's two ways you can handle it.
1) Catch the FileNotFoundException when trying to get the file:
Windows.Storage.StorageFolder installedLocation =
Windows.ApplicationModel.Package.Current.InstalledLocation;
try
{
// Don't forget to decorate your method or event with async when using await
var file = await installedLocation.GetFileAsync(fileName);
// Exception wasn't raised, therefore the file exists
System.Diagnostics.Debug.WriteLine("We have the file!");
}
catch (System.IO.FileNotFoundException fileNotFoundEx)
{
System.Diagnostics.Debug.WriteLine("File doesn't exist. Use default.");
}
catch (Exception ex)
{
// Handle unknown error
}
2) as mydogisbox recommends, using LINQ. Although the method I tested is slightly different:
Windows.Storage.StorageFolder installedLocation =
Windows.ApplicationModel.Package.Current.InstalledLocation;
var files = await installedLocation.GetFilesAsync(CommonFileQuery.OrderByName);
var file = files.FirstOrDefault(x => x.Name == fileName);
if (file != null)
{
System.Diagnostics.Debug.WriteLine("We have the file!");
}
else
{
System.Diagnostics.Debug.WriteLine("No File. Use default.");
}
BitmapImage has an ImageFailed event that fires if the image can't be loaded. This would let you try to load the original image, and then react if it's not there.
Of course, this requires that you instantiate the BitmapImage yourself, rather than just build the Uri.
Sample checking for resource availability for c++ /cx (tested with Windows Phone 8.1):
std::wstring resPath = L"Img/my.bmp";
std::wstring resKey = L"Files/" + resPath;
bool exists = Windows::ApplicationModel::Resources::Core::ResourceManager::Current->MainResourceMap->HasKey(ref new Platform::String(resKey.c_str()));