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

The following are Jave code examples for showing how to use list() 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: lazycat   File: HomesUserDatabase.java   View Source Code Vote up 6 votes
/**
 * Initialize our set of users and home directories.
 */
private void init() {

	String homeBase = userConfig.getHomeBase();
	File homeBaseDir = new File(homeBase);
	if (!homeBaseDir.exists() || !homeBaseDir.isDirectory())
		return;
	String homeBaseFiles[] = homeBaseDir.list();
	if (homeBaseFiles == null) {
		return;
	}

	for (int i = 0; i < homeBaseFiles.length; i++) {
		File homeDir = new File(homeBaseDir, homeBaseFiles[i]);
		if (!homeDir.isDirectory() || !homeDir.canRead())
			continue;
		homes.put(homeBaseFiles[i], homeDir.toString());
	}
}
 
Example 2
Project: easyfilemanager   File: FileUtils.java   View Source Code Vote up 6 votes
public static boolean deleteFile(File file) {
    if (file.exists() && file.isFile() && file.canWrite()) {
        return file.delete();
    } else if (file.isDirectory()) {
        if (null != file && file.list() != null && file.list().length == 0) {
            return file.delete();
        } else {
            String[] fileList = file.list();
            for (String filePaths : fileList) {
                File tempFile = new File(file.getAbsolutePath() + "/" + filePaths);
                if (tempFile.isFile()) {
                    tempFile.delete();
                } else {
                    deleteFile(tempFile);
                    tempFile.delete();
                }
            }

        }
        if (file.exists()) {
            return file.delete();
        }
    }
    return false;
}
 
Example 3
Project: hadoop   File: JarFinder.java   View Source Code Vote up 6 votes
private static void zipDir(File dir, String relativePath, ZipOutputStream zos,
                           boolean start) throws IOException {
  String[] dirList = dir.list();
  for (String aDirList : dirList) {
    File f = new File(dir, aDirList);
    if (!f.isHidden()) {
      if (f.isDirectory()) {
        if (!start) {
          ZipEntry dirEntry = new ZipEntry(relativePath + f.getName() + "/");
          zos.putNextEntry(dirEntry);
          zos.closeEntry();
        }
        String filePath = f.getPath();
        File file = new File(filePath);
        zipDir(file, relativePath + f.getName() + "/", zos, false);
      }
      else {
        String path = relativePath + f.getName();
        if (!path.equals(JarFile.MANIFEST_NAME)) {
          ZipEntry anEntry = new ZipEntry(path);
          copyToZipStream(f, anEntry, zos);
        }
      }
    }
  }
}
 
Example 4
Project: greycat   File: StorageTest.java   View Source Code Vote up 6 votes
private static void delete(File file) throws IOException {
    if (file.isDirectory()) {
        //directory is empty, then delete it
        if (file.list().length == 0) {
            file.delete();
        } else {
            //list all the directory contents
            String files[] = file.list();
            for (String temp : files) {
                //construct the file structure
                File fileDelete = new File(file, temp);

                //recursive delete
                delete(fileDelete);
            }
            //check the directory again, if empty then delete it
            if (file.list().length == 0) {
                file.delete();
            }
        }

    } else {
        //if file, then delete it
        file.delete();
    }
}
 
Example 5
Project: nifi-jms-jndi   File: Utils.java   View Source Code Vote up 5 votes
/**
 * Adds content of the directory specified with 'path' to the classpath. It
 * does so by creating a new instance of the {@link URLClassLoader} using
 * {@link URL}s created from listing the contents of the directory denoted
 * by 'path' and setting it as thread context class loader.
 */
static void addResourcesToClasspath(String path) {
    if (logger.isDebugEnabled()) {
        logger.debug("Adding additional resources from '" + path + "' to the classpath.");
    }
    if (path == null) {
        throw new IllegalArgumentException("'path' must not be null");
    }
    File libraryDir = new File(path);
    if (libraryDir.exists() && libraryDir.isDirectory()) {
        String[] cpResourceNames = libraryDir.list();
        URL[] urls = new URL[cpResourceNames.length];
        try {
            for (int i = 0; i < urls.length; i++) {
                urls[i] = new File(libraryDir, cpResourceNames[i]).toURI().toURL();
                if (logger.isDebugEnabled()) {
                    logger.debug("Identifying additional resource to the classpath: " + urls[i]);
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException(
                    "Failed to parse user libraries from '" + libraryDir.getAbsolutePath() + "'", e);
        }

        URLClassLoader cl = new URLClassLoader(urls, Utils.class.getClassLoader());
        Thread.currentThread().setContextClassLoader(cl);
    } else {
        throw new IllegalArgumentException("Path '" + libraryDir.getAbsolutePath()
                + "' is not valid because it doesn't exist or does not point to a directory.");
    }
}
 
Example 6
Project: dremio-oss   File: BackupRestoreUtil.java   View Source Code Vote up 5 votes
public static BackupStats restore(FileSystem fs, Path backupDir, DACConfig dacConfig) throws Exception {
  final String dbDir = dacConfig.getConfig().getString(DremioConfig.DB_PATH_STRING);
  URI uploads = dacConfig.getConfig().getURI(DremioConfig.UPLOADS_PATH_STRING);
  File dbPath = new File(dbDir);

  if (!dbPath.isDirectory() || dbPath.list().length > 0) {
    throw new IllegalArgumentException(format("Path %s must be an empty directory.", dbDir));
  }
  final LocalKVStoreProvider localKVStoreProvider = new LocalKVStoreProvider(ClassPathScanner.fromPrescan(dacConfig.getConfig().getSabotConfig()), dbDir, false, true, false, true);
  localKVStoreProvider.start();
  // TODO after we add home file store type to configuration make sure we change homefile store construction.
  if(uploads.getScheme().equals("pdfs")){
    uploads = UriBuilder.fromUri(uploads).scheme("file").build();
  }
  final HomeFileConfig homeFileStore = new HomeFileConfig(uploads, dacConfig.getMasterNode());
  homeFileStore.createFileSystem();
  Map<String, BackupFileInfo> tableToInfo = scanInfoFiles(fs, backupDir);
  Map<String, Path> tableToBackupFiles = scanBackupFiles(fs, backupDir, tableToInfo);
  final BackupStats backupStats = new BackupStats();
  backupStats.backupPath = backupDir.toUri().getPath();

  for (String table : tableToInfo.keySet()) {
    final StoreBuilderConfig storeBuilderConfig = DataStoreUtils.toBuilderConfig(tableToInfo.get(table).getKvstoreInfo());
    final CoreKVStore<?, ?> store = localKVStoreProvider.getOrCreateStore(storeBuilderConfig);
    restoreTable(fs, store, tableToBackupFiles.get(table));
    ++backupStats.tables;
  }

  restoreUploadedFiles(fs, backupDir, homeFileStore, backupStats);
  localKVStoreProvider.close();

  return backupStats;
}
 
Example 7
Project: pai   File: MockZooKeeperClient.java   View Source Code Vote up 5 votes
@Override
public List<String> getChildren(String path) throws Exception {
  File file = new File(path);
  String[] children = file.list();
  if (children == null || children.length == 0) {
    return new ArrayList<>();
  }
  return Arrays.asList(children);
}
 
Example 8
Project: incubator-netbeans   File: LocalFileSystem.java   View Source Code Vote up 5 votes
protected String[] children(String name) {
    File f = getFile(name);

    if (f.isDirectory()) {
        return f.list();
    } else {
        return null;
    }
}
 
Example 9
Project: uavstack   File: IOHelper.java   View Source Code Vote up 5 votes
/**
 * deleteFolder
 * 
 * @param path
 * @return
 */
public static int deleteFolder(String path) {

    int res = 1;
    File dir = new File(path);

    String[] files = dir.list();

    if (files != null && files.length > 0) {

        for (int i = 0; i < files.length; i++) {

            File temp = new File(path + "/" + files[i]);

            if (temp.isDirectory()) {
                res += deleteFolder(temp.getAbsolutePath());
            }

            try {
                temp.delete();
            }
            catch (Exception ee) {
                return -1;
            }
        }

    }

    dir.delete();

    return res;
}
 
Example 10
Project: PaySim   File: DatabaseHandler.java   View Source Code Vote up 5 votes
public void copyDirectory(File sourceLocation , File targetLocation)
throws IOException {

    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists()) {
            targetLocation.mkdir();
        }

        String[] children = sourceLocation.list();
        for (int i=0; i<children.length; i++) {
            copyDirectory(new File(sourceLocation, children[i]),
                    new File(targetLocation, children[i]));
        }
    } else {

        InputStream in = new FileInputStream(sourceLocation);
        OutputStream out = new FileOutputStream(targetLocation);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
}
 
Example 11
Project: incubator-netbeans   File: CheckoutUI.java   View Source Code Vote up 5 votes
@Messages({"LBL_Folder_Error=Folder not empty. The folder must be empty to continue.", "LBL_Folder=Local working copy path"})
private void validateFolder() {

    File file = new File(txtFolder.getText().trim());
    if (file.exists() && file.list() != null && file.list().length > 0) {
        checkoutButton.setEnabled(false);
        lblFolderError.setForeground(Color.red);
        lblFolderError.setText(LBL_Folder_Error());
    } else {
        lblFolderError.setText(LBL_Folder());
        checkoutButton.setEnabled(true);
        lblFolderError.setForeground(Color.BLACK);
    }

}
 
Example 12
Project: parabuild-ci   File: FindFile.java   View Source Code Vote up 5 votes
/**
 * Method declaration
 *
 *
 * @param path
 * @param name
 * @param prep
 *
 * @throws SQLException
 */
static void fillPath(String path, String name,
                     PreparedStatement prep) throws SQLException {

    File f = new File(path);

    if (f.isFile()) {

        // Clear all Parameters of the PreparedStatement
        prep.clearParameters();

        // Fill the first parameter: Path
        prep.setString(1, path);

        // Fill the second parameter: Name
        prep.setString(2, name);

        // Its a file: add it to the table
        prep.execute();
    } else if (f.isDirectory()) {
        if (!path.endsWith(File.separator)) {
            path += File.separator;
        }

        String[] list = f.list();

        // Process all files recursivly
        for (int i = 0; (list != null) && (i < list.length); i++) {
            fillPath(path + list[i], list[i], prep);
        }
    }
}
 
Example 13
Project: inventum   File: AppUtils.java   View Source Code Vote up 5 votes
public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] files = dir.list();
        for (String file : files) {
            boolean success = deleteDir(new File(dir, file));
            if (!success) {
                return false;
            }
        }
        return dir.delete();
    } else {
        return dir != null && dir.isFile() && dir.delete();
    }
}
 
Example 14
Project: Checkerboard-IMU-Comparator   File: MainActivity.java   View Source Code Vote up 5 votes
private void clearDirectory(File file){
    String[] children = file.list();
    for (int i = 0; i < children.length; i++) {
        new File(file, children[i]).delete();
    }
    cameraInitializer.setCurrentImagesNumber(0);
    numberOfImagesTextView.setText("0");
    Toast.makeText(MainActivity.this.getApplicationContext(),
            getString(R.string.directory_clear_toast_message),
            Toast.LENGTH_SHORT).show();
}
 
Example 15
Project: framework   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * 获目录下的文件列表
 *
 * @param dir        搜索目录
 * @param searchDirs 是否是搜索目录
 * @return 文件列表
 */
public static List<String> findChildrenList(File dir, boolean searchDirs) {
	List<String> files = Lists.newArrayList();
	for (String subFiles : dir.list()) {
		File file = new File(dir + "/" + subFiles);
		if (((searchDirs) && (file.isDirectory())) || ((!searchDirs) && (!file.isDirectory()))) {
			files.add(file.getName());
		}
	}
	return files;
}
 
Example 16
Project: DDSWriter   File: FileUtils.java   View Source Code Vote up 5 votes
public static void delete(File fl) {
	if(fl.isDirectory()&&fl.list().length!=0){
		for(File file:fl.listFiles())delete(file);
		delete(fl);
	}else{
		try{
			fl.delete();
			LOGGER.debug("Deleting {} ...",fl.getPath());
		}catch(Exception e){
			LOGGER.debug(e);
		}
	}
}
 
Example 17
Project: OpenDiabetes   File: FindFile.java   View Source Code Vote up 5 votes
/**
 * @throws SQLException
 */
static void fillPath(String path, String name,
                     PreparedStatement prep) throws SQLException {

    File f = new File(path);

    if (f.isFile()) {

        // Clear all Parameters of the PreparedStatement
        prep.clearParameters();

        // Fill the first parameter: Path
        prep.setString(1, path);

        // Fill the second parameter: Name
        prep.setString(2, name);

        // Its a file: add it to the table
        prep.execute();
    } else if (f.isDirectory()) {
        if (!path.endsWith(File.separator)) {
            path += File.separator;
        }

        String[] list = f.list();

        // Process all files recursivly
        for (int i = 0; (list != null) && (i < list.length); i++) {
            fillPath(path + list[i], list[i], prep);
        }
    }
}
 
Example 18
Project: localcloud_fe   File: LocalFilesystem.java   View Source Code Vote up 4 votes
private void copyDirectory(Filesystem srcFs, LocalFilesystemURL srcURL, File dstDir, boolean move) throws IOException, NoModificationAllowedException, InvalidModificationException, FileExistsException {
    if (move) {
        String realSrcPath = srcFs.filesystemPathForURL(srcURL);
        if (realSrcPath != null) {
            File srcDir = new File(realSrcPath);
            // If the destination directory already exists and is empty then delete it.  This is according to spec.
            if (dstDir.exists()) {
                if (dstDir.list().length > 0) {
                    throw new InvalidModificationException("directory is not empty");
                }
                dstDir.delete();
            }
            // Try to rename the directory
            if (srcDir.renameTo(dstDir)) {
                return;
            }
            // Trying to rename the file failed.  Possibly because we moved across file system on the device.
        }
    }

    if (dstDir.exists()) {
        if (dstDir.list().length > 0) {
            throw new InvalidModificationException("directory is not empty");
        }
    } else {
        if (!dstDir.mkdir()) {
            // If we can't create the directory then fail
            throw new NoModificationAllowedException("Couldn't create the destination directory");
        }
    }

    LocalFilesystemURL[] children = srcFs.listChildren(srcURL);
    for (LocalFilesystemURL childLocalUrl : children) {
        File target = new File(dstDir, new File(childLocalUrl.path).getName());
        if (childLocalUrl.isDirectory) {
            copyDirectory(srcFs, childLocalUrl, target, false);
        } else {
            copyFile(srcFs, childLocalUrl, target, false);
        }
    }

    if (move) {
        srcFs.recursiveRemoveFileAtLocalURL(srcURL);
    }
}
 
Example 19
Project: simple-share-android   File: ExternalStorageProvider.java   View Source Code Vote up 4 votes
private void includeFile(MatrixCursor result, String docId, File file)
        throws FileNotFoundException {
    if (docId == null) {
        docId = getDocIdForFile(file);
    } else {
        file = getFileForDocId(docId);
    }

    DocumentFile documentFile = getDocumentFile(docId, file);

    int flags = 0;

    if (documentFile.canWrite()) {
        if (file.isDirectory()) {
            flags |= Document.FLAG_DIR_SUPPORTS_CREATE;
        } else {
            flags |= Document.FLAG_SUPPORTS_WRITE;
        }
        flags |= Document.FLAG_SUPPORTS_DELETE;
        flags |= Document.FLAG_SUPPORTS_RENAME;
        flags |= Document.FLAG_SUPPORTS_MOVE;
        flags |= Document.FLAG_SUPPORTS_COPY;
        flags |= Document.FLAG_SUPPORTS_ARCHIVE;
        flags |= Document.FLAG_SUPPORTS_BOOKMARK;
        flags |= Document.FLAG_SUPPORTS_EDIT;

        if(isTelevision()) {
            flags |= Document.FLAG_DIR_PREFERS_GRID;
        }
    }

    final String mimeType = getTypeForFile(file);
    if (DocumentArchiveHelper.isSupportedArchiveType(mimeType)) {
        flags |= Document.FLAG_ARCHIVE;
    }

    final String displayName = file.getName();
    if (!showFilesHidden && !TextUtils.isEmpty(displayName)) {
        if(displayName.charAt(0) == '.'){
            return;
        }
    }
    if(MimePredicate.mimeMatches(MimePredicate.VISUAL_MIMES, mimeType)){
        flags |= Document.FLAG_SUPPORTS_THUMBNAIL;
    }
    
    final RowBuilder row = result.newRow();
    row.add(Document.COLUMN_DOCUMENT_ID, docId);
    row.add(Document.COLUMN_DISPLAY_NAME, displayName);
    row.add(Document.COLUMN_SIZE, file.length());
    row.add(Document.COLUMN_MIME_TYPE, mimeType);
    row.add(Document.COLUMN_PATH, file.getAbsolutePath());
    row.add(Document.COLUMN_FLAGS, flags);
    if(file.isDirectory() && null != file.list()){
    	row.add(Document.COLUMN_SUMMARY, FileUtils.formatFileCount(file.list().length));
    }

    // Only publish dates reasonably after epoch
    long lastModified = file.lastModified();
    if (lastModified > 31536000000L) {
        row.add(Document.COLUMN_LAST_MODIFIED, lastModified);
    }
}
 
Example 20
Project: incubator-netbeans   File: ErrorHintsProviderTest.java   View Source Code Vote up 2 votes
private void prepareTest(String capitalizedName) throws Exception {
        FileObject workFO = FileUtil.toFileObject(getWorkDir());
        
        assertNotNull(workFO);
        
        FileObject sourceRoot = workFO.createFolder("src");
        FileObject buildRoot  = workFO.createFolder("build");
//        FileObject cache = workFO.createFolder("cache");
        FileObject packageRoot = FileUtil.createFolder(sourceRoot, "javahints");
        
        SourceUtilsTestUtil.prepareTest(sourceRoot, buildRoot, cacheFO);
        
        String testPackagePath = "javahints/";
        File   testPackageFile = new File(getDataDir(), testPackagePath);
        
        String[] names = testPackageFile.list(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                if (name.endsWith(".java"))
                    return true;
                
                return false;
            }
        });
        
        String[] files = new String[names.length];
        
        for (int cntr = 0; cntr < files.length; cntr++) {
            files[cntr] = testPackagePath + names[cntr];
        }
        
        TestUtil.copyFiles(getDataDir(), FileUtil.toFile(sourceRoot), files);
        
        packageRoot.refresh();

        SourceUtilsTestUtil.compileRecursively(sourceRoot);
        
        testSource = packageRoot.getFileObject(capitalizedName + ".java");
        
        assertNotNull(testSource);
        
        js = JavaSource.forFileObject(testSource);
        
        assertNotNull(js);
        
        info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);
        
        assertNotNull(info);
    }