Extracting “filename” from full path in actionscript 3

女生的网名这么多〃 提交于 2019-12-22 06:56:47

问题


Does AS3 have a built in class / function to extract "filename" from a complete path. e.g. I wish to extract "filename.doc" from full path "C:\Documents and Settings\All Users\Desktop\filename.doc"


回答1:


For Air, you can try using File Class to extract file name

var file:File=new File("path_string");   
//path_string example "C:\\Windows\\myfile.txt"  
var filename:String = file.name;



回答2:


First you want to find the last occurrence of / or \ in the path, do that using this:

var fSlash: int = fullPath.lastIndexOf("/");
var bSlash: int = fullPath.lastIndexOf("\\"); // reason for the double slash is just to escape the slash so it doesn't escape the quote!!!
var slashIndex: int = fSlash > bSlash ? fSlash : bSlash;

That will give you the index in the string that is right BEFORE that last slash. So then to return the portion of the string after that, you add one to the index (moving it past the last slash) and return the remainder of the string

var docName: String = fullPath.substr(slashIndex + 1);

To do this as a simple to use function, do this:

function getFileName(fullPath: String) : String
{
    var fSlash: int = fullPath.lastIndexOf("/");
    var bSlash: int = fullPath.lastIndexOf("\\"); // reason for the double slash is just to escape the slash so it doesn't escape the quote!!!
    var slashIndex: int = fSlash > bSlash ? fSlash : bSlash;
    return fullPath.substr(slashIndex + 1);
}

var fName: String = getFileName(myFullPath);



回答3:


Couldn't you just do something basic like:

string filename = filename.substring(filename.lastIndexOf("\\") + 1)

I know it's not a single function call, but it should work just the same.

Edited based on @Bryan Grezeszak's comment.




回答4:


Apparently you can use the File class, or more specifically, the File.separator static member if you're working with AIR. It should return "/" or "\", which you can plug in to @cmptrgeekken's suggestion.




回答5:


Try this:

var file_ :File = new File("C:/Usea_/Dtop/sinim (1).jpg"); // or url variable ... whatever//

file_ = file_.parent;

trace(file_.url);



回答6:


You can use something like this to do the job :

var tmpArray:Array<String>;
var fileName:String;

tmpArray = fullFilePath.split("\");
fileName = tmpArray.pop();

You have to take care if you are using Unix file system ("/") or Windows file system ("\").



来源:https://stackoverflow.com/questions/743739/extracting-filename-from-full-path-in-actionscript-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!