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

The following are Jave code examples for showing how to use isDirectory() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Mzip-Android   File: ZipArchive.java   View Source Code Vote up 8 votes
public static void zip(String targetPath, String destinationFilePath, String password) {
    try {
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

        if (password.length() > 0) {
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
            parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
            parameters.setPassword(password);
        }

        ZipFile zipFile = new ZipFile(destinationFilePath);

        File targetFile = new File(targetPath);
        if (targetFile.isFile()) {
            zipFile.addFile(targetFile, parameters);
        } else if (targetFile.isDirectory()) {
            zipFile.addFolder(targetFile, parameters);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 2
Project: TYT   File: DataCleanUtil.java   View Source Code Vote up 6 votes
/**
 * 删除指定目录下文件及目录
 *
 * @param deleteThisPath
 * @return
 */
public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
    if (!TextUtils.isEmpty(filePath)) {
        try {
            File file = new File(filePath);
            if (file.isDirectory()) {// 如果下面还有文件
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFolderFile(files[i].getAbsolutePath(), true);
                }
            }
            if (deleteThisPath) {
                if (!file.isDirectory()) {// 如果是文件,删除
                    file.delete();
                } else {// 目录
                    if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除
                        file.delete();
                    }
                }
            }
        } catch (Exception e) {
            // Auto-generated catch block
            e.printStackTrace();
        }
    }
}
 
Example 3
Project: Moenagade   File: FileUtils.java   View Source Code Vote up 6 votes
/**
 * Moves a file to a directory.
 *
 * @param srcFile the file to be moved
 * @param destDir the destination file
 * @param createDestDir If <code>true</code> create the destination directory,
 * otherwise if <code>false</code> throw an IOException
 * @throws NullPointerException if source or destination is <code>null</code>
 * @throws FileExistsException if the destination file exists
 * @throws IOException if source or destination is invalid
 * @throws IOException if an IO error occurs moving the file
 * @since Commons IO 1.4
 */
public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) throws IOException {
    if (srcFile == null) {
        throw new NullPointerException("Source must not be null");
    }
    if (destDir == null) {
        throw new NullPointerException("Destination directory must not be null");
    }
    if (!destDir.exists() && createDestDir) {
        destDir.mkdirs();
    }
    if (!destDir.exists()) {
        throw new FileNotFoundException("Destination directory '" + destDir +
                "' does not exist [createDestDir=" + createDestDir +"]");
    }
    if (!destDir.isDirectory()) {
        throw new IOException("Destination '" + destDir + "' is not a directory");
    }
    moveFile(srcFile, new File(destDir, srcFile.getName()));
}
 
Example 4
Project: OpenDA   File: BBTemplateFile.java   View Source Code Vote up 6 votes
public void generateTargetFile(File fileOrDir) {
    File workingDir = fileOrDir.isDirectory() ? fileOrDir : fileOrDir.getParentFile();

    File templateFile = new File(workingDir,templateFileName);
    File targetFile = new File(workingDir, targetFileName);
    File valuesFile = new File(workingDir, valuesFileName);

    String[] contents = FileSupport.readContentOfFile(templateFile);

    Properties valueProperties = new Properties();
    try {
        valueProperties.load(new FileInputStream(valuesFile));
    } catch (IOException e) {
        throw new RuntimeException("Problem reading key value pairs from valuesFile " + valuesFile.getAbsolutePath());
    }
    for (String keyId: valueProperties.stringPropertyNames()) {
        String value = valueProperties.getProperty(keyId);
        TemplateKeyDefinition keyDefinition = getKeyDefinitionByKeyId(keyId);
        if (keyDefinition == null) continue;
        writeValueToContent(contents, keyDefinition, value);
    }

    FileSupport.writeContentOfFile(targetFile,contents);
}
 
Example 5
Project: buddybox   File: ModelImpl.java   View Source Code Vote up 6 votes
private List<Song> listSongs(File directory) {
    ArrayList<Song> ret = new ArrayList<>();

    if (!directory.exists()) {
        System.out.println("Directory does not exist: " + directory);
        return ret;
    }

    File[] files = directory.listFiles();
    if (files == null) return ret;

    for (File file : files) {
        if (file.isDirectory()) {
            ret.addAll(listSongs(file));
        } else {
            Song song = tryToReadSong(file);
            if (song == null) continue;
            ret.add(song);
        }
    }
    return ret;
}
 
Example 6
Project: downloadmanager   File: DownloadManager.java   View Source Code Vote up 6 votes
/**
 * Set the local destination for the downloaded file to a path within
 * the public external storage directory (as returned by
 * {@link Environment#getExternalStoragePublicDirectory(String)}).
 * <p>
 * The downloaded file is not scanned by MediaScanner. But it can be
 * made scannable by calling {@link #allowScanningByMediaScanner()}.
 *
 * @param dirType the directory type to pass to {@link Environment#getExternalStoragePublicDirectory(String)}
 * @param subPath the path within the external directory, including the
 *                destination filename
 * @return this object
 * @throws IllegalStateException If the external storage directory
 *                               cannot be found or created.
 */
public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
    File file = Environment.getExternalStoragePublicDirectory(dirType);
    if (file == null) {
        throw new IllegalStateException("Failed to get external storage public directory");
    } else if (file.exists()) {
        if (!file.isDirectory()) {
            throw new IllegalStateException(file.getAbsolutePath() +
                    " already exists and is not a directory");
        }
    } else {
        if (!file.mkdirs()) {
            throw new IllegalStateException("Unable to create directory: " +
                    file.getAbsolutePath());
        }
    }
    setDestinationFromBase(file, subPath);
    return this;
}
 
Example 7
Project: LuaViewPlayground   File: FileUtil.java   View Source Code Vote up 6 votes
/**
 * delete a file
 *
 * @param file
 */
public static void delete(File file) {
    if (file != null && file.exists()) {
        if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null) {
                for (File child : children) {
                    delete(child);
                }
            }
            file.delete();
        } else {
            file.delete();
        }
    }
}
 
Example 8
Project: n4js   File: FileBasedWorkspace.java   View Source Code Vote up 6 votes
/**
 *
 * @param location
 *            project directory containing manifest.n4mf directly
 */
public void registerProject(URI location) {
	if (location.lastSegment().isEmpty()) {
		throw new IllegalArgumentException("lastSegment may not be empty");
	}

	if (!projectElementHandles.containsKey(location)) {
		LazyProjectDescriptionHandle lazyDescriptionHandle = createLazyDescriptionHandle(location, false);
		projectElementHandles.put(location, lazyDescriptionHandle);
		for (String libraryPath : lazyDescriptionHandle.createProjectElementHandle().getLibraryPaths()) {
			URI libraryFolder = location.appendSegment(libraryPath);
			File lib = new File(java.net.URI.create(libraryFolder.toString()));
			if (lib.isDirectory()) {
				for (File archive : lib.listFiles()) {
					if (archive.getName().endsWith(IN4JSArchive.NFAR_FILE_EXTENSION_WITH_DOT)) {
						URI archiveLocation = URI.createURI(archive.toURI().toString());
						projectElementHandles.put(archiveLocation,
								createLazyDescriptionHandle(archiveLocation, true));
					}
				}
			}
		}
	}
}
 
Example 9
Project: Simpler   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * 根据文件路径,检查文件是否不大于指定大小
 *
 * @param filepath 文件路径
 * @param maxSize  最大
 * @return 是否
 */
public static boolean checkFileSize(String filepath, int maxSize) {

    File file = new File(filepath);
    if (!file.exists() || file.isDirectory()) {
        return false;
    }
    if (file.length() <= maxSize * 1024) {
        return true;
    } else {
        return false;
    }
}
 
Example 10
Project: Moenagade   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * Finds files within a given directory (and optionally its
 * subdirectories). All files found are filtered by an IOFileFilter.
 * <p>
 * If your search should recurse into subdirectories you can pass in
 * an IOFileFilter for directories. You don't need to bind a
 * DirectoryFileFilter (via logical AND) to this filter. This method does
 * that for you.
 * <p>
 * An example: If you want to search through all directories called
 * "temp" you pass in <code>FileFilterUtils.NameFileFilter("temp")</code>
 * <p>
 * Another common usage of this method is find files in a directory
 * tree but ignoring the directories generated CVS. You can simply pass
 * in <code>FileFilterUtils.makeCVSAware(null)</code>.
 *
 * @param directory  the directory to search in
 * @param fileFilter  filter to apply when finding files.
 * @param dirFilter  optional filter to apply when finding subdirectories.
 * If this parameter is <code>null</code>, subdirectories will not be included in the
 * search. Use TrueFileFilter.INSTANCE to match all directories.
 * @return an collection of java.io.File with the matching files
 * @see org.apache.commons.io.filefilter.FileFilterUtils
 * @see org.apache.commons.io.filefilter.NameFileFilter
 */
public static Collection<File> listFiles(
        File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) {
    if (!directory.isDirectory()) {
        throw new IllegalArgumentException(
                "Parameter 'directory' is not a directory");
    }
    if (fileFilter == null) {
        throw new NullPointerException("Parameter 'fileFilter' is null");
    }

    //Setup effective file filter
    IOFileFilter effFileFilter = FileFilterUtils.and(fileFilter,
        FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));

    //Setup effective directory filter
    IOFileFilter effDirFilter;
    if (dirFilter == null) {
        effDirFilter = FalseFileFilter.INSTANCE;
    } else {
        effDirFilter = FileFilterUtils.and(dirFilter,
            DirectoryFileFilter.INSTANCE);
    }

    //Find files
    Collection<File> files = new java.util.LinkedList<File>();
    innerListFiles(files, directory,
        FileFilterUtils.or(effFileFilter, effDirFilter));
    return files;
}
 
Example 11
Project: Jenisys3   File: ResourcePackManager.java   View Source Code Vote up 5 votes
public ResourcePackManager(File path) {
    if (!path.exists()) {
        path.mkdirs();
    } else if (!path.isDirectory()) {
        throw new IllegalArgumentException(Server.getInstance().getLanguage()
                .translateString("nukkit.resources.invalid-path", path.getName()));
    }

    List<ResourcePack> loadedResourcePacks = new ArrayList<>();
    for (File pack : path.listFiles()) {
        try {
            ResourcePack resourcePack = null;

            if (!pack.isDirectory()) { //directory resource packs temporarily unsupported
                switch (Files.getFileExtension(pack.getName())) {
                    case "zip":
                        resourcePack = new ZippedResourcePack(pack);
                        break;
                    default:
                        Server.getInstance().getLogger().warning(Server.getInstance().getLanguage()
                                .translateString("nukkit.resources.unknown-format", pack.getName()));
                        break;
                }
            }

            if (resourcePack != null) {
                loadedResourcePacks.add(resourcePack);
                this.resourcePacksById.put(resourcePack.getPackId(), resourcePack);
            }
        } catch (IllegalArgumentException e) {
            Server.getInstance().getLogger().warning(Server.getInstance().getLanguage()
                    .translateString("nukkit.resources.fail", pack.getName(), e.getMessage()));
        }
    }

    this.resourcePacks = loadedResourcePacks.toArray(new ResourcePack[loadedResourcePacks.size()]);
    Server.getInstance().getLogger().info(Server.getInstance().getLanguage()
            .translateString("nukkit.resources.success", String.valueOf(this.resourcePacks.length)));
}
 
Example 12
Project: CS4500GroupProject   File: FileDialog.java   View Source Code Vote up 5 votes
private void saveOpenDialogDir(JFileChooser fc) {
    try {
        File currentDir = fc.getCurrentDirectory();
        if (currentDir != null && currentDir.exists() && currentDir.isDirectory()) {
            luytenPrefs.setFileOpenCurrentDirectory(currentDir.getAbsolutePath());
        }
    } catch (Exception e) {
        Luyten.showExceptionDialog("Exception!", e);
    }
}
 
Example 13
Project: chiefproject   File: CheckSave.java   View Source Code Vote up 5 votes
public int checkSaveL(String saveName){
	int judge;
	File saveF = new File(savePath + saveName);
	if(saveF.exists() && saveF.isDirectory()){
		judge = 1;
	}else{
		judge = 0;
	}
	return judge;
}
 
Example 14
Project: PlusGram   File: MediaController.java   View Source Code Vote up 5 votes
public void checkSaveToGalleryFiles() {
    try {
        File telegramPath = new File(Environment.getExternalStorageDirectory(), "Telegram");
        File imagePath = new File(telegramPath, "Telegram Images");
        imagePath.mkdir();
        File videoPath = new File(telegramPath, "Telegram Video");
        videoPath.mkdir();

        if (saveToGallery) {
            if (imagePath.isDirectory()) {
                new File(imagePath, ".nomedia").delete();
            }
            if (videoPath.isDirectory()) {
                new File(videoPath, ".nomedia").delete();
            }
        } else {
            if (imagePath.isDirectory()) {
                new File(imagePath, ".nomedia").createNewFile();
            }
            if (videoPath.isDirectory()) {
                new File(videoPath, ".nomedia").createNewFile();
            }
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}
 
Example 15
Project: AgentWorkbench   File: Zipper.java   View Source Code Vote up 5 votes
/**
 * This method will evaluate the given folder and it's sub-folder.
 * The containing File objects will be stored in the Vector 'fileList'
 * @param folder
 */
private void evaluateFolder(String srcFolder) {
	
	File folder = new File(srcFolder);
	String listOfFiles[] = folder.list();
	for (int i = 0; i < listOfFiles.length; i++) {
		
		// --- consider the exclude pattern ---------------------
		boolean includeFile = false;
		if (excludePattern==null) {
			includeFile=true;
		} else {
			if (listOfFiles[i].contains(excludePattern)) {
				includeFile=false;
			} else {
				includeFile=true;
			}
		}
		
		// --- If the current file should be included -----------
		if (includeFile==true) {
			File sngFileObject = new File(srcFolder + File.separator + listOfFiles[i]);
			if (sngFileObject.isDirectory()) {
				this.evaluateFolder(sngFileObject.getAbsolutePath());
			} else {
				this.fileList.add(sngFileObject);
			}
		}
	} // end for
	
}
 
Example 16
Project: AndiCar   File: FileUtils.java   View Source Code Vote up 5 votes
@SuppressWarnings("TryFinallyCanBeTryWithResources")
public static void unzipFile(File zipFile, File targetDirectory) throws IOException {

    ZipInputStream zis = new ZipInputStream(
            new BufferedInputStream(new FileInputStream(zipFile)));
    try {
        ZipEntry ze;
        int count;
        byte[] buffer = new byte[8192];
        while ((ze = zis.getNextEntry()) != null) {
            File file = new File(targetDirectory, ze.getName());
            File dir = ze.isDirectory() ? file : file.getParentFile();
            if (!dir.isDirectory() && !dir.mkdirs()) {
                throw new FileNotFoundException("Failed to ensure directory: " +
                        dir.getAbsolutePath());
            }
            if (ze.isDirectory()) {
                continue;
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            try {
                while ((count = zis.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, count);
                }
            }
            finally {
                fileOutputStream.close();
            }
        }
    }
    finally {
        zis.close();
    }
}
 
Example 17
Project: Hotspot-master-devp   File: FileUtils.java   View Source Code Vote up 5 votes
public static FileInputStream openInputStream(File file) throws IOException {
    if(file.exists()) {
        if(file.isDirectory()) {
            throw new IOException("File \'" + file + "\' exists but is a directory");
        } else if(!file.canRead()) {
            throw new IOException("File \'" + file + "\' cannot be read");
        } else {
            return new FileInputStream(file);
        }
    } else {
        throw new FileNotFoundException("File \'" + file + "\' does not exist");
    }
}
 
Example 18
Project: uavstack   File: MSCPBoot.java   View Source Code Vote up 4 votes
private URL[] loadJars(final Set<String> featureJars, String... libPaths) {

        List<File> files = new ArrayList<File>();

        for (String libPath : libPaths) {

            File plusRoot = new File(libPath);

            if (!plusRoot.exists() || !plusRoot.isDirectory())
                return null;

            File[] jarFiles = plusRoot.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String name) {

                    if (name.endsWith(".jar") && !featureJars.contains(name)) {
                        return true;
                    }

                    return false;
                }

            });

            if (jarFiles == null || jarFiles.length == 0) {
                continue;
            }

            files.addAll(Arrays.asList(jarFiles));
        }

        List<URL> jarURLs = new ArrayList<URL>();

        for (File jar : files) {
            try {
                jarURLs.add(jar.toURI().toURL());
            }
            catch (MalformedURLException e) {
                // ignore
            }
        }

        URL[] jarURLArray = new URL[jarURLs.size()];
        jarURLs.toArray(jarURLArray);
        return jarURLArray;
    }
 
Example 19
Project: QN-ACTR-Release   File: Scatter.java   View Source Code Vote up 4 votes
/**
 * Whether the given file is accepted by this filter.
 */
@Override
public boolean accept(File f) {
	String name = f.getName().toLowerCase();
	return name.endsWith(extension) || f.isDirectory();
}
 
Example 20
Project: siiMobilityAppKit   File: LocalFilesystem.java   View Source Code Vote up 4 votes
@Override
public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
		String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
       boolean create = false;
       boolean exclusive = false;

       if (options != null) {
           create = options.optBoolean("create");
           if (create) {
               exclusive = options.optBoolean("exclusive");
           }
       }

       // Check for a ":" character in the file to line up with BB and iOS
       if (path.contains(":")) {
           throw new EncodingException("This path has an invalid \":\" in it.");
       }

       LocalFilesystemURL requestedURL;

       // Check whether the supplied path is absolute or relative
       if (directory && !path.endsWith("/")) {
           path += "/";
       }
       if (path.startsWith("/")) {
       	requestedURL = localUrlforFullPath(normalizePath(path));
       } else {
       	requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
       }

       File fp = new File(this.filesystemPathForURL(requestedURL));

       if (create) {
           if (exclusive && fp.exists()) {
               throw new FileExistsException("create/exclusive fails");
           }
           if (directory) {
               fp.mkdir();
           } else {
               fp.createNewFile();
           }
           if (!fp.exists()) {
               throw new FileExistsException("create fails");
           }
       }
       else {
           if (!fp.exists()) {
               throw new FileNotFoundException("path does not exist");
           }
           if (directory) {
               if (fp.isFile()) {
                   throw new TypeMismatchException("path doesn't exist or is file");
               }
           } else {
               if (fp.isDirectory()) {
                   throw new TypeMismatchException("path doesn't exist or is directory");
               }
           }
       }

       // Return the directory
       return makeEntryForURL(requestedURL);
}