到目前为止,我在当前目录中创建了一个名为“src”的文件夹
new File("src").mkdir();
然后如果 src 文件夹中有任何 .java 文件,我想将它们存储在数组中
JavaFileObject javaFileObjects[] = new JavaFileObject[]{};
有人可以提供一个解决方案,用 src 文件夹中的 .java 文件填充这个数组。
是的,正如评论所说,使用 aFileFilter
并检查.java
扩展名。
像这样:
File parentDirectory = new File("src");
File [] javaFiles = parentDirectory.listFiles(new RecursiveExtensionFileFilter(".java"));
这是一个您可能会发现有用的过滤器类:
package util;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileFilter;
/**
* RecursiveExtensionFileFilter for filtering only Word .doc files
* @author Michael
* @link
* @since 2/13/13 10:21 AM
*/
public class RecursiveExtensionFileFilter implements FileFilter {
public static final String DEFAULT_WORD_EXTENSION = ".doc";
private final String extension;
private final boolean makeLowerCase;
public RecursiveExtensionFileFilter(String extension) {
this(extension, false);
}
public RecursiveExtensionFileFilter(String extension, boolean makeLowerCase) {
if (StringUtils.isBlank(extension))
throw new IllegalArgumentException("file extension cannot be blank or null");
this.extension = extension;
this.makeLowerCase = makeLowerCase;
}
@Override
public boolean accept(File pathname) {
boolean isWordDocOrDirectory = false;
if (pathname != null) {
if (pathname.isDirectory()) {
isWordDocOrDirectory = true;
} else {
String absolutePath = pathname.getAbsolutePath();
if (this.makeLowerCase) {
absolutePath = absolutePath.toLowerCase();
}
isWordDocOrDirectory = (absolutePath.lastIndexOf(this.extension) == (absolutePath.length() - this.extension.length()));
}
}
return isWordDocOrDirectory;
}
}