java.io.File.list()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(10.0k)|赞(0)|评价(0)|浏览(165)

本文整理了Java中java.io.File.list()方法的一些代码示例,展示了File.list()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。File.list()方法的具体详情如下:
包路径:java.io.File
类名称:File
方法名:list

File.list介绍

[英]Returns an array of strings with the file names in the directory represented by this file. The result is null if this file is not a directory.

The entries . and .. representing the current and parent directory are not returned as part of the list.
[中]返回一个字符串数组,其中包含此文件表示的目录中的文件名。如果此文件不是目录,则结果为null。
条目。和表示当前目录和父目录的文件不会作为列表的一部分返回。

代码示例

代码示例来源:origin: jenkinsci/jenkins

/**
 * Deletes a directory if it's empty.
 */
private void deleteIfEmpty(File dir) {
  String[] r = dir.list();
  if(r==null)     return; // can happen in a rare occasion
  if(r.length==0)
    dir.delete();
}

代码示例来源:origin: libgdx/libgdx

public static boolean isEmptyDirectory (String destination) {
  if (new File(destination).exists()) {
    return new File(destination).list().length == 0;
  } else {
    return true;
  }
}

代码示例来源:origin: stackoverflow.com

File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here"); 
if (dir.isDirectory()) 
{
  String[] children = dir.list();
  for (int i = 0; i < children.length; i++)
  {
    new File(dir, children[i]).delete();
  }
}

代码示例来源:origin: stackoverflow.com

File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);

代码示例来源:origin: AdoptOpenJDK/jitwatch

private void addGroovyJars(List<String> classpathEntries)
{
  File libDir = groovyLibDir.toFile();
  String[] jars = libDir.list(new FilenameFilter()
  {
    @Override
    public boolean accept(File dir, String name)
    {
      return name.endsWith(".jar");
    }
  });
  for (String jar : jars)
  {
    classpathEntries.add(new File(libDir, jar).getAbsolutePath());
  }
}

代码示例来源:origin: stackoverflow.com

public class Testing extends Activity {
 private static final String TAG = "TEST";
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   File appsDir = new File("/data/app");
   String[] files = appsDir.list();
   for (int i = 0 ; i < files.length ; i++ ) {
     Log.d(TAG, "File: "+files[i]);
   }
 }

代码示例来源:origin: apache/hbase

File tmpFolder = new File(ClassLoaderTestHelper.localDirPath(conf), "tmp");
if (tmpFolder.exists()) { // Clean up the tmp folder
 File[] files = tmpFolder.listFiles();
 if (files != null) {
  for (File f: files) {
   f.delete();
File innerJarFile = ClassLoaderTestHelper.buildJar(
 folder, className, null, ClassLoaderTestHelper.localDirPath(conf));
File targetJarFile = new File(innerJarFile.getParent(), jarName);
ClassLoaderTestHelper.addJarFilesToJar(targetJarFile, libPrefix, innerJarFile);
Path path = new Path(targetJarFile.getAbsolutePath());
ClassLoader parent = TestCoprocessorClassLoader.class.getClassLoader();
ClassLoader classLoader = CoprocessorClassLoader.getClassLoader(path, parent, "112", conf);
assertNotNull("Classloader should be created", classLoader);
String fileToLookFor = "." + className + ".jar";
String[] files = tmpFolder.list();
if (files != null) {
 for (String f: files) {

代码示例来源:origin: androidannotations/androidannotations

private void findPossibleLocations(String basePath, String targetPath, String variantPart, List<String> possibleLocations) {
  String[] directories = new File(basePath + targetPath).list();
  if (directories == null) {
    return;
  }
  if (variantPart.startsWith("/") || variantPart.startsWith("\\")) {
    variantPart = variantPart.substring(1);
  }
  for (String directory : directories) {
    String possibleLocation = targetPath + "/" + directory;
    File variantDir = new File(basePath + possibleLocation);
    if (variantDir.isDirectory() && variantPart.toLowerCase().startsWith(directory.toLowerCase())) {
      String remainingPart = variantPart.substring(directory.length());
      if (remainingPart.length() == 0) {
        possibleLocations.add(possibleLocation);
        addPossibleSplitLocations(basePath, possibleLocation, possibleLocations);
      } else {
        findPossibleLocations(basePath, possibleLocation, remainingPart, possibleLocations);
      }
    }
  }
}

代码示例来源:origin: apache/incubator-gobblin

@Test
 public void testCleanStateStore() throws IOException {
  File tmpDir = Files.createTempDir();
  tmpDir.deleteOnExit();

  FileSystem fs = FileSystem.getLocal(new Configuration());

  FsDatasetStateStore store = new FsDatasetStateStore(fs, tmpDir.getAbsolutePath());

  store.persistDatasetState("dataset1", new JobState.DatasetState("job1", "job1_id1"));
  store.persistDatasetState("dataset1", new JobState.DatasetState("job1", "job1_id2"));
  store.persistDatasetState("dataset1", new JobState.DatasetState("job2", "job2_id1"));
  store.persistDatasetState("", new JobState.DatasetState("job3", "job3_id1"));

  Properties props = new Properties();

  props.setProperty(ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY, tmpDir.getAbsolutePath());
  props.setProperty("selection.timeBased.lookbackTime", "0m");

  TimeBasedDatasetStoreDatasetFinder datasetFinder = new TimeBasedDatasetStoreDatasetFinder(fs, props);
  List<DatasetStoreDataset> datasets = datasetFinder.findDatasets();

  for (DatasetStoreDataset dataset : datasets) {
   ((CleanableDataset) dataset).clean();
   File jobDir = new File(tmpDir.getAbsolutePath(), dataset.getKey().getStoreName());
   Assert.assertEquals(jobDir.list().length, 1);
  }
 }
}

代码示例来源:origin: stackoverflow.com

public String getReasonForFileDeletionFailureInPlainEnglish(File file) {
  try {
    if (!file.exists())
      return "It doesn't exist in the first place.";
    else if (file.isDirectory() && file.list().length > 0)
      return "It's a directory and it's not empty.";
    else
      return "Somebody else has it open, we don't have write permissions, or somebody stole my disk.";
  } catch (SecurityException e) {
    return "We're sandboxed and don't have filesystem access.";
  }
}

代码示例来源:origin: jeremylong/DependencyCheck

/**
 * Deletes any files extracted from the JAR during analysis.
 */
@Override
public void closeAnalyzer() {
  if (tempFileLocation != null && tempFileLocation.exists()) {
    LOGGER.debug("Attempting to delete temporary files from `{}`", tempFileLocation.toString());
    final boolean success = FileUtils.delete(tempFileLocation);
    if (!success && tempFileLocation.exists()) {
      final String[] l = tempFileLocation.list();
      if (l != null && l.length > 0) {
        LOGGER.warn("Failed to delete the JAR Analyzder's temporary files from `{}`, "
            + "see the log for more details", tempFileLocation.getAbsolutePath());
      }
    }
  }
}

代码示例来源:origin: igniterealtime/Smack

@Override
public void removeAllRawSessionsOf(OmemoDevice userDevice, BareJid contact) {
  File contactsDirectory = hierarchy.getContactsDir(userDevice, contact);
  String[] devices = contactsDirectory.list();
  for (String deviceId : devices != null ? devices : new String[0]) {
    int id = Integer.parseInt(deviceId);
    OmemoDevice device = new OmemoDevice(contact, id);
    File session = hierarchy.getContactsSessionPath(userDevice, device);
    if (!session.delete()) {
      LOGGER.log(Level.WARNING, "Deleting raw OMEMO session " + session.getAbsolutePath() + "failed.");
    }
  }
}

代码示例来源:origin: apache/incubator-gobblin

private static String getClasspathFromPath(File path) {
 if (null == path) {
  return StringUtils.EMPTY;
 }
 if (!path.isDirectory()) {
  return path.getAbsolutePath();
 }
 return Joiner.on(":").skipNulls().join(path.list(FileFileFilter.FILE));
}

代码示例来源:origin: apache/flink

@Override
public FileStatus[] listStatus(final Path f) throws IOException {
  final File localf = pathToFile(f);
  FileStatus[] results;
  if (!localf.exists()) {
    return null;
  }
  if (localf.isFile()) {
    return new FileStatus[] { new LocalFileStatus(localf, this) };
  }
  final String[] names = localf.list();
  if (names == null) {
    return null;
  }
  results = new FileStatus[names.length];
  for (int i = 0; i < names.length; i++) {
    results[i] = getFileStatus(new Path(f, names[i]));
  }
  return results;
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public Set<String> getResourcePaths(String path) {
  String actualPath = (path.endsWith("/") ? path : path + "/");
  Resource resource = this.resourceLoader.getResource(getResourceLocation(actualPath));
  try {
    File file = resource.getFile();
    String[] fileList = file.list();
    if (ObjectUtils.isEmpty(fileList)) {
      return null;
    }
    Set<String> resourcePaths = new LinkedHashSet<>(fileList.length);
    for (String fileEntry : fileList) {
      String resultPath = actualPath + fileEntry;
      if (resource.createRelative(fileEntry).getFile().isDirectory()) {
        resultPath += "/";
      }
      resourcePaths.add(resultPath);
    }
    return resourcePaths;
  }
  catch (IOException ex) {
    if (logger.isWarnEnabled()) {
      logger.warn("Could not get resource paths for " + resource, ex);
    }
    return null;
  }
}

代码示例来源:origin: h2oai/h2o-3

static boolean paramFilesExist(final String paramPath) {
 final File f = new File(paramPath);
 String[] list = f.getParentFile().list(new FilenameFilter() {
  @Override
  public boolean accept(File dir, String name) {
   return name.contains(f.getName());
  }
 });
 return !f.isDirectory() && (f.exists() || (list != null && list.length > 0));
}

代码示例来源:origin: cSploit/android

public static ArrayList<String> getAvailableHijackerSessionFiles() {
 ArrayList<String> files = new ArrayList<String>();
 File storage = new File(mStoragePath);
 if (storage.exists()) {
  String[] children = storage.list();
  if (children != null && children.length > 0) {
   for (String child : children) {
    if (child.endsWith(".dhs"))
     files.add(child);
   }
  }
 }
 return files;
}

代码示例来源:origin: Sable/soot

private static void readStar() {
 String curDir = System.getProperty("user.dir");
 System.out.println("Current system directory is" + curDir);
 File dir = new File(curDir);
 String[] children = dir.list();
 if (children == null) {
  // Either dir does not exist or is not a directory
 } else {
  FilenameFilter filter = new FilenameFilter() {
   public boolean accept(File dir, String name) {
    return name.endsWith(".xml");
   }
  };
  children = dir.list(filter);
  if (children != null) {
   for (String element : children) {
    xmlFileList.add(element);
   }
  }
 }
}

代码示例来源:origin: AdoptOpenJDK/jitwatch

private void addGroovyJars(List<String> classpathEntries)
{
  File libDir = groovyLibDir.toFile();
  String[] jars = libDir.list(new FilenameFilter()
  {
    @Override
    public boolean accept(File dir, String name)
    {
      return name.endsWith(".jar");
    }
  });
  for (String jar : jars)
  {
    classpathEntries.add(new File(libDir, jar).getAbsolutePath());
  }
}

代码示例来源:origin: stackoverflow.com

// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()

相关文章