下面列出了java.io.File#isDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
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;
}
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);
}
}
/** 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];
}
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;
}
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);
}
}
@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));
}
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");
}
/**
* 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();
}
}
/**
* 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();
}
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;
}
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());
}
}
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;
}
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
if (isWorkspaceFile(file)) {
return true;
}
return false;
}
/**
* 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);
}
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();
}
}
}
/**
* 通过类型获取目录路径
*
* @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 + "/";
}
/**
* 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);
}
private boolean checkPathExist(String path) {
File file = new File(path);
return file.exists() && !file.isDirectory();
}
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;
}