javascript getFiles() 不是文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21631437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getFiles() not folders
提问by Ghoul Fool
I've got several files in a temporary folder. I can load them into Photoshop with scripting the following:
我在一个临时文件夹中有几个文件。我可以使用以下脚本将它们加载到 Photoshop 中:
var sourceFolder = Folder("C:\temp");
if (sourceFolder != null)
{
var fileList = sourceFolder.getFiles();
}
This is all good, but how do I ignore directories (such as C:\temp\waffles) that might also be in there also.
这一切都很好,但是我如何忽略可能也在其中的目录(例如 C:\temp\waffles)。
I understand that I could do a check for valid image extensions and then add them to a new filelist array and then load that. I don't think the search option TopDirectoryOnly is valid here.
我知道我可以检查有效的图像扩展名,然后将它们添加到新的文件列表数组中,然后加载它。我认为搜索选项 TopDirectoryOnly 在这里无效。
回答by
Since getFiles() "Returns an array of File and Folder objects" You will need to iterate over each of the objects returned and test to see what kind of object it is. From Adobe's Creative Suite 5 Javacript Tools Guide
由于 getFiles() “返回文件和文件夹对象的数组”,您将需要遍历返回的每个对象并测试它是什么类型的对象。来自 Adobe 的 Creative Suite 5 Javacript 工具指南
There are several ways to distinguish between a File and a Folder object. For example:if (f instanceof File)...
if (typeof f.open == "undefined")... //Folders do not open.
回答by Pedro Marques
If I use this when getting folder or files, I avoid write if()
later:
如果我在获取文件夹或文件时使用它,我会避免if()
稍后写入:
var fileList = sourceFolder.getFiles(function(f) { return f instanceof File; });
The same when getting only folders:
仅获取文件夹时相同:
var fileList = sourceFolder.getFiles(function(f) { return f instanceof Folder; });
However it is recommended to use the getFiles
function as less as possible because the code will run faster.
但是,建议getFiles
尽可能少地使用该函数,因为代码会运行得更快。
I also use RegExp
objects to pick only specific sub-folders in a folder.
我还使用RegExp
对象仅选择文件夹中的特定子文件夹。
For example, if I set a regular expression like the 'regthis' var as below. The folders collected with 'getFiles' will be the one that its name:
A) Must have '12345678' at the end or a uppercase letter before '12345678';
B) Must also have one of the 2 characters ('_' or a 'c') before A;
C) Must have 1 lowercase letter 'a-v' before B+A;
D) Must not have 'x' or 'y' or 'z' before C+B+A;
例如,如果我设置一个像下面的“ regthis”变量的正则表达式。使用'getFiles'收集的文件夹将是其名称的文件夹:
A) 必须在末尾有'12345678' 或在'12345678' 之前有一个大写字母;
B) 在 A 之前还必须有 2 个字符之一('_' 或一个 'c');
C) B+A 前必须有 1 个小写字母 'av';
D) 在 C+B+A 之前不能有 'x' 或 'y' 或 'z';
var ID_ = '12345678';
var regthis = new RegExp( '([^x-z]{1}[a-v]{1}[_|c]{1})([A-Z]?'+ID_+'?)$','i');
var sameIDfolder = Folder(myFolder).getFiles(regthis);