下面列出了java.io.File#isHidden ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private List<String> getAllFileNames(File dir) throws IOException {
List<String> names = new ArrayList<String>();
File[] files = dir.listFiles();
if ( files==null ) {
throw new FileNotFoundException(String.format("[%s] is not an existing directory", dir));
}
for ( File file : files ) {
if ( !file.isHidden() ) {
if ( file.isDirectory() && !m_flat ) {
names.addAll(getAllFileNames(file));
} else {
names.add(RelativeContentFactory.toRelativeFilePath(file, m_dir));
}
}
}
return names;
}
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
File f = path.toFile();
if (!f.isHidden() && f.getName().endsWith(".cfg")) {
configDispatcher.processConfigFile(f);
}
} else if (kind == ENTRY_DELETE) {
// Detect if a service specific configuration file was removed. We want to
// notify the service in this case with an updated empty configuration.
File configFile = path.toFile();
if (configFile.isHidden() || configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) {
return;
}
configDispatcher.fileRemoved(configFile.getAbsolutePath());
}
}
private void mkdir(String directory) {
printDebug("mkdir : '" + directory + "'");
try {
String currentDir = getEnvironment().getCurrentDirectory();
String dirFullPath = FileUtil.buildFilePath(currentDir, directory);
File dir = new File(dirFullPath);
if ( dir.exists() ) {
String type = "" ;
if ( dir.isFile() ) {
type = "file" + ( dir.isHidden() ? "/hidden" : "" ) ;
}
if ( dir.isDirectory() ) {
type = "directory" + ( dir.isHidden() ? "/hidden" : "" ) ;
}
print("'"+ directory +"' already exists (" + type + ")");
}
else {
DirUtil.createDirectory(dir);
print("Directory '"+ directory +"' created");
}
} catch (Exception e) {
print("Error: Cannot create '"+ directory +"' directory");
print("Exception '" + e.getClass().getCanonicalName() + "' : " + e.getMessage());
}
}
public List<PluginWrapper> generatePluginWrappers() {
List<PluginWrapper> mapList = new ArrayList<PluginWrapper>();
File pluginWorkspaceDir = new File(pluginWorkspace);
for (File file : pluginWorkspaceDir.listFiles()) {
Map<String, String> map = new HashMap<String, String>();
try {
if (file.isDirectory() && !file.isHidden() && !file.getName().equals("tempCompressedPluginFileRepository")) {// avoid .svn dir and temp repository
String configFilePath = file.getAbsolutePath() + "//config.conf";
FileInputStream fileInpuStream = new FileInputStream(configFilePath);
DataInputStream dataInputStream = new DataInputStream(fileInpuStream);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(dataInputStream));
String strLine;
//Read File Line By Line
while ((strLine = bufferReader.readLine()) != null) {
addToMap(strLine, map);
}
//Close resource
bufferReader.close();
dataInputStream.close();
fileInpuStream.close();
PluginWrapper pluginWrapper = new PluginWrapper(file.getAbsolutePath(), map);
mapList.add(pluginWrapper);
}
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
return mapList;
}
/**
* 删除目录
* @param dir对象
*/
public static Boolean removeDirectory(File dir){
Boolean state = null;
if(dir.isDirectory()){
state = org.apache.commons.io.FileUtils.deleteQuietly(dir);
if(state == false){
//清空内容
String[] extensions = null;//后缀名{"doc", "pdf"}
boolean recursive = true;//是否递归
Collection<File> files = FileUtils.listFiles(dir, extensions, recursive);
// 迭代输出
for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
File file = iterator.next();
if(!file.isHidden()){//不是隐蔽文件
//清空内容
try {
org.apache.commons.io.FileUtils.writeStringToFile(file, "", "UTF-8");
state = file.delete();
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
if (logger.isErrorEnabled()) {
logger.error("删除目录",e);
}
}
}
}
}
}
return state;
}
protected byte[] load(String filename) {
File file = IO.file(filename);
if (file.exists()) {
if (!file.isFile() || file.isDirectory()) {
return null;
}
// a normal file on the file system
Log.trace("Resource file exists", "name", name, "file", file);
long lastModif;
try {
lastModif = Files.getLastModifiedTime(file.toPath()).to(TimeUnit.MILLISECONDS);
} catch (IOException e) {
// maybe it doesn't exist anymore
lastModif = U.time();
}
if (lastModif > this.lastModified || !filename.equals(cachedFileName)) {
Log.debug("Loading resource file", "name", name, "file", file);
this.lastModified = file.lastModified();
this.hidden = file.isHidden();
return IO.loadBytes(filename);
} else {
Log.trace("Resource file not modified", "name", name, "file", file);
return bytes;
}
} else {
// it might not exist or it might be on the classpath or compressed in a JAR
Log.trace("Trying to load classpath resource", "name", name, "file", file);
this.hidden = false;
return IO.loadBytes(filename);
}
}
private void getExpiredMarkers(File file, List<String> expired) {
if (file.isFile()) {
if (!file.isHidden() && file.getName().endsWith(AbstractHoplogOrganizer.EXPIRED_HOPLOG_EXTENSION)) {
expired.add(file.getName());
}
return;
}
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
getExpiredMarkers(f, expired);
}
}
}
@Override
protected Object doInBackground(Object[] params) {
List<FileBean> fileBeenList = new ArrayList<>();
if (file.isDirectory()) {
File[] filesArray = file.listFiles();
if (filesArray != null) {
List<File> fileList = new ArrayList<>();
Collections.addAll(fileList, filesArray); //把数组转化成list
Collections.sort(fileList, FileUtil.comparator); //按照名字排序
for (File f : fileList) {
if (f.isHidden()) continue;
FileBean fileBean = new FileBean();
fileBean.setName(f.getName());
fileBean.setPath(f.getAbsolutePath());
fileBean.setFileType(FileUtil.getFileType(f));
fileBean.setChildCount(FileUtil.getFileChildCount(f));
fileBean.setSize(f.length());
fileBean.setHolderType(0);
fileBeenList.add(fileBean);
FileBean lineBean = new FileBean();
lineBean.setHolderType(1);
fileBeenList.add(lineBean);
}
}
}
beanList = fileBeenList;
return fileBeenList;
}
private static void zipFile(final File fileToZip, final String fileName, final ZipOutputStream zipOut) throws IOException {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
if (fileName.endsWith("/")) {
zipOut.putNextEntry(new ZipEntry(fileName));
zipOut.closeEntry();
} else {
zipOut.putNextEntry(new ZipEntry(fileName + "/"));
zipOut.closeEntry();
}
final File[] children = fileToZip.listFiles();
for (final File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
return;
}
final FileInputStream fis = new FileInputStream(fileToZip);
final ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
private void loadSnippetsInSpacewalkDir(List<CobblerSnippet> snippetFiles) {
for (File path : CobblerSnippet.getSpacewalkSnippetsDir().listFiles()) {
if (path.isFile() && !path.isHidden()) {
snippetFiles.add(CobblerSnippet.loadReadOnly(path));
}
}
}
/**
* 获取文件夹目录列表
* @param path 文件路径
* @param catalogCallback 目录回调通知
* @param ignoreCatelog 忽略目录
* @param layer 目录层级
* @param curLayer 当前层级
* @return 文件夹目录列表集合
*/
private static List<FileUtils.FileList> getFolderLists(final String path, final CatalogCallback catalogCallback,
final String[] ignoreCatelog, final int layer, final int curLayer) {
// 当前层级大于想要的层级则 return
if (curLayer > layer) return new ArrayList<>();
List<FileUtils.FileList> lists = new ArrayList<>();
// 获取文件路径
File baseFile = new File(path);
// 获取子文件
File[] files = baseFile.listFiles();
for (File file : files) {
String name = file.getName();
// 隐藏文件跳过
if (file.isHidden() || name.startsWith(".")) {
continue;
}
// 判断根目录是否需要忽略
if (curLayer != 0 && DevCommonUtils.isContains(baseFile.getName(), ignoreCatelog)) {
return lists;
}
// 属于文件夹才处理
if (file.isDirectory()) {
FileUtils.FileList catalog = new FileUtils.FileList(file,
getFolderLists(file.getAbsolutePath(), catalogCallback, ignoreCatelog, layer, curLayer + 1));
lists.add(catalog);
// 触发回调
if (catalogCallback != null) {
// lineNumber 固定传 1 只是为了增加默认空格间距
catalogCallback.callback(name, curLayer + 1, name + "." + name);
}
}
}
return lists;
}
private void traverse (File directory)
// ---------------------------------------------------------------------------------//
{
if (rootFolderData.progressPanel.cancelled)
return;
File[] files = directory.listFiles ();
if (files == null || files.length == 0)
{
// System.out.println ("Empty folder : " + directory.getAbsolutePath ());
return;
}
for (File file : files)
{
if (rootFolderData.progressPanel.cancelled)
return;
if (file.isHidden ())
continue;
if (file.isDirectory ())
{
if (file.getName ().equalsIgnoreCase ("emulators"))
System.out.println ("ignoring: " + file.getAbsolutePath ());
else
{
rootFolderData.incrementFolders ();
traverse (file);
}
}
else
{
String fileName = file.getName ().toLowerCase ();
if (Utility.validFileType (fileName) && file.length () > 0)
{
rootFolderData.incrementType (file, fileName);
if ((rootFolderData.totalDisks % 250) == 0)
publish (rootFolderData);
}
}
}
}
private FileFilter createFileFilter(final ProcessContext context) {
final long minSize = context.getProperty(MIN_SIZE).asDataSize(DataUnit.B).longValue();
final Double maxSize = context.getProperty(MAX_SIZE).asDataSize(DataUnit.B);
final long minAge = context.getProperty(MIN_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
final Long maxAge = context.getProperty(MAX_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
final boolean ignoreHidden = context.getProperty(IGNORE_HIDDEN_FILES).asBoolean();
final Pattern filePattern = Pattern.compile(context.getProperty(FILE_FILTER).getValue());
final String indir = context.getProperty(DIRECTORY).evaluateAttributeExpressions().getValue();
final boolean recurseDirs = context.getProperty(RECURSE).asBoolean();
final String pathPatternStr = context.getProperty(PATH_FILTER).getValue();
final Pattern pathPattern = (!recurseDirs || pathPatternStr == null) ? null : Pattern.compile(pathPatternStr);
final boolean keepOriginal = context.getProperty(KEEP_SOURCE_FILE).asBoolean();
return new FileFilter() {
@Override
public boolean accept(final File file) {
if (minSize > file.length()) {
return false;
}
if (maxSize != null && maxSize < file.length()) {
return false;
}
final long fileAge = System.currentTimeMillis() - file.lastModified();
if (minAge > fileAge) {
return false;
}
if (maxAge != null && maxAge < fileAge) {
return false;
}
if (ignoreHidden && file.isHidden()) {
return false;
}
if (pathPattern != null) {
Path reldir = Paths.get(indir).relativize(file.toPath()).getParent();
if (reldir != null && !reldir.toString().isEmpty()) {
if (!pathPattern.matcher(reldir.toString()).matches()) {
return false;
}
}
}
//Verify that we have at least read permissions on the file we're considering grabbing
if (!Files.isReadable(file.toPath())) {
return false;
}
//Verify that if we're not keeping original that we have write permissions on the directory the file is in
if (keepOriginal == false && !Files.isWritable(file.toPath().getParent())) {
return false;
}
return filePattern.matcher(file.getName()).matches();
}
};
}
private void fill(File f) {
File[] folders = null;
if (fileFilter != null)
folders = f.listFiles(fileFilter);
else
folders = f.listFiles();
if(f.getAbsolutePath().trim().equalsIgnoreCase(currentCategory.path.trim()) == true)
{
this.setTitle(currentCategory.title + ": /");
}
else
{
this.setTitle(currentCategory.title + ": " + f.getName());
}
int fileSize = this.getResources().getIdentifier("fileSize", "string", _context.getPackageName());
List<FileInfo> dirs = new ArrayList<FileInfo>();
List<FileInfo> files = new ArrayList<FileInfo>();
try {
for (File file : folders) {
if (file.isDirectory() && !file.isHidden())
//si es un directorio en el data se ponemos la contante folder
dirs.add(new FileInfo(file.getName(),
Constants.FOLDER, file.getAbsolutePath(),
true, false));
else {
if (!file.isHidden())
files.add(new FileInfo(file.getName(),
getString(fileSize) + ": "
+ file.length(),
file.getAbsolutePath(), false, false));
}
}
} catch (Exception e) {
e.printStackTrace();
}
Collections.sort(dirs);
Collections.sort(files);
dirs.addAll(files);
/*if (!f.getName().equalsIgnoreCase(
Environment.getExternalStorageDirectory().getName())) {
if (f.getParentFile() != null)
//si es un directorio padre en el data se ponemos la contante adeacuada
dirs.add(0, new FileInfo("..",
Constants.PARENT_FOLDER, f.getParent(),
false, true));
}*/
if (!f.getAbsolutePath().equalsIgnoreCase(
currentCategory.path)) {
if (f.getParentFile() != null)
//si es un directorio padre en el data se ponemos la contante adeacuada
dirs.add(0, new FileInfo("..",
Constants.PARENT_FOLDER, f.getParent(),
false, true));
}
int file_row = this.getResources().getIdentifier("file_row", "layout", _context.getPackageName());
fileArrayListAdapter = new FileArrayAdapter(FileChooserActivity.this,
file_row, dirs);
//ListView lv = (ListView)findViewById(R.id.list);
//lv.setOnItemClickListener(this);
//lv.setAdapter(fileArrayListAdapter);
this.setListAdapter(fileArrayListAdapter);
}
/**
* Returns whether a file is hidden or not.
*/
public boolean isHiddenFile(File f) {
return f.isHidden();
}
private FileFilter createFileFilter(final ProcessContext context) {
final long minSize = context.getProperty(MIN_SIZE).asDataSize(DataUnit.B).longValue();
final Double maxSize = context.getProperty(MAX_SIZE).asDataSize(DataUnit.B);
final long minAge = context.getProperty(MIN_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
final Long maxAge = context.getProperty(MAX_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
final boolean ignoreHidden = context.getProperty(IGNORE_HIDDEN_FILES).asBoolean();
final Pattern filePattern = Pattern.compile(context.getProperty(FILE_FILTER).getValue());
final String indir = context.getProperty(DIRECTORY).evaluateAttributeExpressions().getValue();
final boolean recurseDirs = context.getProperty(RECURSE).asBoolean();
final String pathPatternStr = context.getProperty(PATH_FILTER).getValue();
final Pattern pathPattern = (!recurseDirs || pathPatternStr == null) ? null : Pattern.compile(pathPatternStr);
return new FileFilter() {
@Override
public boolean accept(final File file) {
if (minSize > file.length()) {
return false;
}
if (maxSize != null && maxSize < file.length()) {
return false;
}
final long fileAge = System.currentTimeMillis() - file.lastModified();
if (minAge > fileAge) {
return false;
}
if (maxAge != null && maxAge < fileAge) {
return false;
}
if (ignoreHidden && file.isHidden()) {
return false;
}
if (pathPattern != null) {
Path reldir = Paths.get(indir).relativize(file.toPath()).getParent();
if (reldir != null && !reldir.toString().isEmpty()) {
if (!pathPattern.matcher(reldir.toString()).matches()) {
return false;
}
}
}
//Verify that we have at least read permissions on the file we're considering grabbing
if (!Files.isReadable(file.toPath())) {
return false;
}
return filePattern.matcher(file.getName()).matches();
}
};
}
/**
* Returns whether a file is hidden or not.
*/
public boolean isHiddenFile(File f) {
return f.isHidden();
}
/**
* Recursively read the scripts directory and add them to our macros vector
* holding area
*
* @param vector
* @param path
* @param directory
*/
private static void loadScripts(Vector vector,
String path,
File directory) {
Macro macro;
File[] macroFiles = directory.listFiles();
if(macroFiles == null || macroFiles.length == 0)
return;
Arrays.sort(macroFiles, new MacroCompare());
for(int i = 0; i < macroFiles.length; i++) {
File file = macroFiles[i];
String fileName = file.getName();
if(file.isHidden()) {
/* do nothing! */
continue;
}
else if(file.isDirectory()) {
Vector<String> subvector = new Vector<String>();
subvector.addElement(fileName.replace('_',' '));
loadScripts(subvector,path + fileName + '/',file);
// if we do not want empty directories to show up uncomment this
// line. It is uncommented here.
if(subvector.size() != 1)
vector.addElement(subvector);
}
else {
if (InterpreterDriverManager.isScriptSupported(fileName)) {
String fn = fileName.replace('_',' ');
int index = fn.lastIndexOf('.');
if (index > 0) {
fn = fn.substring(0,index);
}
macro = new Macro (fn, file.getAbsolutePath(),fileName);
vector.addElement(macro);
}
}
}
}
/**
* Returns whether a file is hidden or not.
*/
public boolean isHiddenFile(File f) {
return f.isHidden();
}
/**
* Scans file(s) recursively starting with the named file, and, for each
* file that passes the filter, submits the task.
*
* @param file
* Either a URL, a plain file or directory containing files
* to be processed.
*
* @throws InterruptedException
* if the thread is interrupted while queuing tasks.
*/
private void process2(final File file) throws InterruptedException {
if (file.isHidden()) {
// ignore hidden files.
return;
}
if (file.isDirectory()) {
if (log.isInfoEnabled())
log.info("Scanning directory: " + file);
// filter is optional.
final File[] files = filter == null ? file.listFiles() : file
.listFiles(filter);
for (final File f : files) {
process2(f);
}
} else {
/*
* Processing a standard file.
*/
accept(file);
}
}