Java Code Examples for java.io.File#isDirectory()

The following examples show how to use java.io.File#isDirectory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public File findScriptForDm( AbstractApplication app, Instance scopedInstance ) {

	File result = null;
	String targetId = findTargetId( app, InstanceHelpers.computeInstancePath( scopedInstance ));
	if( targetId != null ) {
		File targetDir = new File( findTargetDirectory( targetId ), Constants.PROJECT_SUB_DIR_SCRIPTS );
		if( targetDir.isDirectory()){
			for( File f : Utils.listAllFiles( targetDir )) {
				if( f.getName().toLowerCase().contains( Constants.SCOPED_SCRIPT_AT_DM_CONFIGURE_SUFFIX )) {
					result = f;
					break;
				}
			}
		}
	}

	return result;
}
 
Example 2
Source Project: gemfirexd-oss   File: DataExtractorTest.java    License: Apache License 2.0 6 votes vote down vote up
static int countLinesInFile(String fileName) throws IOException {
  int count = 0;
  File file = new File(fileName);
  if (file.isDirectory()) {
    throw new RuntimeException("Cannot count lines in a directory");
  } else {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line = reader.readLine(); 
    while (line != null) {
      count++;
      line = reader.readLine();
    }
    reader.close();
  }
  return count;
}
 
Example 3
Source Project: cuba   File: App.java    License: Apache License 2.0 6 votes vote down vote up
protected void initHomeDir() {
    String homeDir = System.getProperty(DesktopAppContextLoader.HOME_DIR_SYS_PROP);
    if (StringUtils.isBlank(homeDir)) {
        homeDir = getDefaultHomeDir();
    }
    homeDir = StringSubstitutor.replaceSystemProperties(homeDir);
    System.setProperty(DesktopAppContextLoader.HOME_DIR_SYS_PROP, homeDir);

    File file = new File(homeDir);
    if (!file.exists()) {
        boolean success = file.mkdirs();
        if (!success) {
            System.out.println("Unable to create home dir: " + homeDir);
            System.exit(-1);
        }
    }
    if (!file.isDirectory()) {
        System.out.println("Invalid home dir: " + homeDir);
        System.exit(-1);
    }
}
 
Example 4
Source Project: science-journal   File: AccountsUtils.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns the existing files directories for all signed-in accounts. */
private static File[] getFilesDirsForAllAccounts(Context context) {
  try {
    File parentDir = getAccountsParentDirectory(context);
    if (parentDir.exists() && parentDir.isDirectory()) {
      // Filter out files that don't have an account key.
      File[] files = parentDir.listFiles((f) -> getAccountKeyFromFile(context, f) != null);
      if (files != null) {
        return files;
      }
    }
  } catch (Exception e) {
    if (Log.isLoggable(TAG, Log.ERROR)) {
      Log.e(TAG, "Failed to get files directories for all accounts.", e);
    }
  }

  return new File[0];
}
 
Example 5
Source Project: MicroReader   File: CacheUtil.java    License: MIT License 6 votes vote down vote up
public static long getFolderSize(File file) {
    long size = 0;
    try {
        File[] fileList = file.listFiles();
        for (File aFileList : fileList) {
            // 如果下面还有文件
            if (aFileList.isDirectory()) {
                size = size + getFolderSize(aFileList);
            } else {
                size = size + aFileList.length();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return size;
}
 
Example 6
Source Project: litchi   File: ZipUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static void compressbyType(File src, ZipOutputStream zos, String baseDir) {
	if (!src.exists()) {
		return;
	}
	if (LOGGER.isDebugEnabled()) {
		LOGGER.debug("压缩 {}{}", baseDir, src.getName());
	}
	if (src.isFile()) {
		compressFile(src, zos, baseDir);
	} else if (src.isDirectory()) {
		compressDir(src, zos, baseDir);
	}
}
 
Example 7
Source Project: gocd   File: SvnMaterial.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {
    Revision revision = revisionContext.getLatestRevision();
    File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);
    LOGGER.debug("Updating to revision: {} in workingdirectory {}", revision, workingDir);
    outputStreamConsumer.stdOutput(format("[%s] Start updating %s at revision %s from %s", GoConstants.PRODUCT_NAME, updatingTarget(), revision.getRevision(), url));
    boolean shouldDoFreshCheckout = !workingDir.isDirectory() || isRepositoryChanged(workingDir);
    if (shouldDoFreshCheckout) {
        freshCheckout(outputStreamConsumer, new SubversionRevision(revision), workingDir);
    } else {
        cleanupAndUpdate(outputStreamConsumer, new SubversionRevision(revision), workingDir);
    }
    LOGGER.debug("done with update");
    outputStreamConsumer.stdOutput(format("[%s] Done.\n", GoConstants.PRODUCT_NAME));
}
 
Example 8
Source Project: hottub   File: Basic.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void testFile(File f, boolean writeable, long length)
    throws Exception
{
    if (!f.exists()) fail(f, "does not exist");
    if (!f.isFile()) fail(f, "is not a file");
    if (f.isDirectory()) fail(f, "is a directory");
    if (!f.canRead()) fail(f, "is not readable");
    if (!Util.isPrivileged() && f.canWrite() != writeable)
        fail(f, writeable ? "is not writeable" : "is writeable");
    int rwLen = 6;
    if (f.length() != length) fail(f, "has wrong length");
}
 
Example 9
Source Project: filechooser   File: FileChooserActivity.java    License: MIT License 5 votes vote down vote up
/**
 * Called when the user selects a File
 *
 * @param file The file that was selected
 */
@Override
public void onFileSelected(File file) {
    if (file != null) {
        if (file.isDirectory()) {
            replaceFragment(file);
        } else {
            finishWithResult(file);
        }
    } else {
        Toast.makeText(FileChooserActivity.this, R.string.error_selecting_file,
                Toast.LENGTH_SHORT).show();
    }
}
 
Example 10
/**
 * Returns a string that represents a directory or a file in the FileChooser component.
 * A string with all upper case letters is returned for a directory.
 * A string with all lower case letters is returned for a file.
 */
@Override
public String getSystemDisplayName(File f) {
    String displayName = super.getSystemDisplayName(f);

    return f.isDirectory() ? displayName.toUpperCase() : displayName.
            toLowerCase();
}
 
Example 11
private static List<File> listDirs(File d) {
    List<File> ret = new ArrayList<>();
    if (d.isDirectory()) {
        for (File f : d.listFiles()) {
            if (f.isDirectory()) {
                ret.add(f);
            }
        }
    }
    return ret;
}
 
Example 12
private void deleteFileOrDirectory(File fileOrDirectory) {
  if (fileOrDirectory.isDirectory()) {
    File[] fileList = fileOrDirectory.listFiles();
    if (fileList != null) {
      for (File file : fileList) {
        deleteFileOrDirectory(file);
      }
    }
  }
  if (!fileOrDirectory.delete()) {
    LOG.warn("Failed to delete file or directory {}", fileOrDirectory.getName());
  }
}
 
Example 13
Source Project: LearningOfThinkInJava   File: Directory.java    License: Apache License 2.0 5 votes vote down vote up
static TreeInfo recurseDirs(File startDir,String regex){
    TreeInfo result=new TreeInfo();
    for(File item:startDir.listFiles()){
        if(item.isDirectory()){
            result.dirs.add(item);
            result.addAll(recurseDirs(item,regex));
        }else {
            if(item.getName().matches(regex)){
                result.files.add(item);
            }
        }
    }
    return result;
}
 
Example 14
Source Project: workcraft   File: FileFilters.java    License: MIT License 5 votes vote down vote up
@Override
public boolean accept(File file) {
    if (file.isDirectory()) {
        return true;
    }
    if (isWorkspaceFile(file)) {
        return true;
    }
    return false;
}
 
Example 15
Source Project: QuickDevFramework   File: FileSizeUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * get file or directory size on disk
 *
 * @param file     file
 * @param sizeType one of the defined SIZE_UNIT type in this class
 * @return file size value
 */
public static double calculateSize(File file, int sizeType) {
    long blockSize = 0;
    try {
        if (file.isDirectory()) {
            blockSize = getDirectorySize(file);
        } else {
            blockSize = getFileSize(file);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, "获取文件大小失败!");
    }
    return getSizeValueByUnit(blockSize, sizeType);
}
 
Example 16
public static List<String> getConfigurationFileList(String path, String configName) {
   if (path == null) {
      return Collections.emptyList();
   } else {
      List<String> fileList = new ArrayList();
      File dir = new File(path);
      if (dir.exists() && dir.isDirectory()) {
         FileFilter filter = new FileFilter() {
            public boolean accept(File pathname) {
               return pathname.isFile();
            }
         };
         File[] files = dir.listFiles(filter);
         String filenames = null;
         Integer oldTot = Integer.valueOf(0);
         if (files == null) {
            return Collections.emptyList();
         } else {
            File[] arr$ = files;
            int len$ = files.length;

            for(int i$ = 0; i$ < len$; ++i$) {
               File f = arr$[i$];
               LOG.info("filename: " + f.getName());
               if (f.getName().contains(configName) && f.getName().endsWith(".xml")) {
                  filenames = f.getName();
                  String[] filename = null;
                  filename = filenames.split("_");
                  String version = null;

                  for(int i = 0; i < filename.length; ++i) {
                     LOG.info("Config filename part " + i + ":" + filename[i]);
                     if (filename[i].endsWith(".xml")) {
                        String fi = filename[i].replace(".xml", "");
                        if (!StringUtils.isEmpty(fi)) {
                           version = fi.replace("v", "");
                           Integer tot = Integer.valueOf(version);
                           if (tot.intValue() > oldTot.intValue()) {
                              if (fileList.size() > 0) {
                                 fileList.remove(0);
                              }

                              fileList.add(f.getAbsolutePath());
                              oldTot = tot;
                           }
                        }
                     }
                  }
               }
            }

            return fileList;
         }
      } else {
         LOG.error("The directory " + path + " does not exist");
         return Collections.emptyList();
      }
   }
}
 
Example 17
/**
 * 通过类型获取目录路径
 *
 * @param type
 * @return
 */
public static String getPathByType(int type) {
    String dir = "/";
    String filePath;

    switch (type) {
        case DIR_TYPE_HOME:
            filePath = DIR_HOME;
            break;

        case DIR_TYPE_CACHE:
            filePath = DIR_CACHE;
            break;

        case DIR_TYPE_IMAGE:
            filePath = DIR_IMAGE;
            break;

        case DIR_TYPE_LOG:
            filePath = DIR_LOG;
            break;

        case DIR_TYPE_APK:
            filePath = DIR_APK;
            break;

        case DIR_TYPE_DOWNLOAD:
            filePath = DIR_DOWNLOAD;
            break;

        case DIR_TYPE_TEMP:
            filePath = DIR_TEMP;
            break;

        case DIR_TYPE_COPY_DB:
            filePath = DIR_COPY_DB;
            break;
        case DIR_TYPE_ZJB:
            filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
                    + File.separator + ResHelper.getString(R.string.app_name);
            break;
        case DIR_TYPE_SYS_IMAGE:
            filePath = DIR_SYS_IMAGE;
            break;
        default:
            filePath = "";
            break;
    }

    File file = new File(filePath);
    if (!file.exists() || !file.isDirectory()) {
        file.mkdirs();
    }

    if (file.exists()) {
        if (file.isDirectory()) {
            dir = file.getPath();
        }
    } else {
        // 文件没创建成功,可能是sd卡不存在,但是还是把路径返回
        dir = filePath;
    }

    return dir + "/";
}
 
Example 18
/**
 * Constructs a <code>FileCacheImageOutputStream</code> that will write
 * to a given <code>outputStream</code>.
 *
 * <p> A temporary file is used as a cache.  If
 * <code>cacheDir</code>is non-<code>null</code> and is a
 * directory, the file will be created there.  If it is
 * <code>null</code>, the system-dependent default temporary-file
 * directory will be used (see the documentation for
 * <code>File.createTempFile</code> for details).
 *
 * @param stream an <code>OutputStream</code> to write to.
 * @param cacheDir a <code>File</code> indicating where the
 * cache file should be created, or <code>null</code> to use the
 * system directory.
 *
 * @exception IllegalArgumentException if <code>stream</code>
 * is <code>null</code>.
 * @exception IllegalArgumentException if <code>cacheDir</code> is
 * non-<code>null</code> but is not a directory.
 * @exception IOException if a cache file cannot be created.
 */
public FileCacheImageOutputStream(OutputStream stream, File cacheDir)
    throws IOException {
    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }
    if ((cacheDir != null) && !(cacheDir.isDirectory())) {
        throw new IllegalArgumentException("Not a directory!");
    }
    this.stream = stream;
    if (cacheDir == null)
        this.cacheFile = Files.createTempFile("imageio", ".tmp").toFile();
    else
        this.cacheFile = Files.createTempFile(cacheDir.toPath(), "imageio", ".tmp")
                              .toFile();
    this.cache = new RandomAccessFile(cacheFile, "rw");

    this.closeAction = StreamCloser.createCloseAction(this);
    StreamCloser.addToQueue(closeAction);
}
 
Example 19
Source Project: CppStyle   File: CppStylePerfPage.java    License: MIT License 4 votes vote down vote up
private boolean checkPathExist(String path) {
	File file = new File(path);
	return file.exists() && !file.isDirectory();
}
 
Example 20
Source Project: AnnihilationPro   File: Game.java    License: MIT License 4 votes vote down vote up
public static boolean loadGameMap(File worldFolder)
	{
//		if(tempWorldDirec == null)
//		{
//			tempWorldDirec = new File(AnnihilationMain.getInstance().getDataFolder()+"/TempWorld");
//			if(!tempWorldDirec.exists())
//				tempWorldDirec.mkdirs();
//		}
		
		if(worldFolder.exists() && worldFolder.isDirectory())
		{
			File[] files = worldFolder.listFiles(new FilenameFilter()
			{
				public boolean accept(File file, String name)
				{
					return name.equalsIgnoreCase("level.dat");
				}
			});
			
			if ((files != null) && (files.length == 1))
			{
				try
				{
					//We have confirmed that the folder has a level.dat
					//Now we should copy all the files into the temp world folder
					
					//worldDirec = worldFolder;
					
					//FileUtils.copyDirectory(worldDirec, tempWorldDirec);
					
					String path = worldFolder.getPath();
					if(path.contains("plugins"))
						path = path.substring(path.indexOf("plugins"));
					WorldCreator cr = new WorldCreator(path);
					//WorldCreator cr = new WorldCreator(new File(worldFolder,"level.dat").toString());
					cr.environment(Environment.NORMAL);
					World mapWorld = Bukkit.createWorld(cr);
					if(mapWorld != null)
					{
						if(GameMap != null)
						{
							GameMap.unLoadMap();
							GameMap = null;
						}
						mapWorld.setAutoSave(false);
						mapWorld.setGameRuleValue("doMobSpawning", "false");
						mapWorld.setGameRuleValue("doFireTick", "false");	
//						File anniConfig = new File(worldFolder,"AnniMapConfig.yml");
//						if(!anniConfig.exists())
//								anniConfig.createNewFile();
						//YamlConfiguration mapconfig = ConfigManager.loadMapConfig(anniConfig);
						Game.GameMap = new GameMap(mapWorld.getName(),worldFolder);
						GameMap.registerListeners(AnnihilationMain.getInstance());
						Game.worldNames.put(worldFolder.getName().toLowerCase(), mapWorld.getName());
						Game.niceNames.put(mapWorld.getName().toLowerCase(),worldFolder.getName());
						return true;
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();
					GameMap = null;
					return false;
				}
			}
		}
		return false;
	}