本文翻译自:Getting the filenames of all files in a folder [duplicate]
Possible Duplicate:可能重复:
Read all files in a folder读取文件夹中的所有文件
I need to create a list with all names of the files in a folder.我需要创建一个列表,其中包含文件夹中所有文件的名称。
For example, if I have:例如,如果我有:
000.jpg012.jpg013.jpg
I want to store them in aArrayList
with[000,012,013]
as values.我想将它们存储在一个带有[000,012,013]
值的ArrayList
。
What's the best way to do it in Java ?在Java中最好的方法是什么?
PS: I'm on Mac OS XPS:我在Mac OS X上
#1楼
参考:/question/NtMv/获取文件夹中所有文件的文件名-重复
#2楼
You could do it like that:你可以这样做:
File folder = new File("your/path");File[] listOfFiles = folder.listFiles();for (int i = 0; i < listOfFiles.length; i++) {if (listOfFiles[i].isFile()) {System.out.println("File " + listOfFiles[i].getName());} else if (listOfFiles[i].isDirectory()) {System.out.println("Directory " + listOfFiles[i].getName());}}
Do you want to only get JPEG files or all files?你想只获得JPEG文件或所有文件吗?
#3楼
Here's how to look in the documentation .以下是如何查看文档 。
First, you're dealing with IO, so look in thejava.io
package .首先,您正在处理IO,所以请查看java.io
包 。
There are two classes that look interesting: FileFilter and FileNameFilter .有两个看起来很有趣的类: FileFilter和FileNameFilter 。When I clicked on the first, it showed me that there was aalistFiles()
method in the File class.当我点击第一个时,它向我展示了File类中有一个listFiles()
方法。And the documentation for that method says:该方法的文档说:
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.返回一个抽象路径名数组,表示此抽象路径名表示的目录中的文件。
Scrolling up in theFile
JavaDoc, I see the constructors.在File
JavaDoc中向上滚动,我看到了构造函数。And that's really all I need to be able to create aFile
instance and calllistFiles()
on it.这就是我需要能够创建一个File
实例并在其上调用listFiles()
。Scrolling still further, I can see some information about how files are named in different operating systems.滚动更进一步,我可以看到有关如何在不同操作系统中命名文件的一些信息。
#4楼
Create aFile
object, passing the directory path to the constructor.创建一个File
对象,将目录路径传递给构造函数。Use thelistFiles()
to retrieve an array ofFile
objects for each file in the directory, and then call thegetName()
method to get the filename.使用listFiles()
为目录中的每个文件检索File
对象的数组,然后调用getName()
方法获取文件名。
List<String> results = new ArrayList<String>();File[] files = new File("/path/to/the/directory").listFiles();//If this pathname does not denote a directory, then listFiles() returns null. for (File file : files) {if (file.isFile()) {results.add(file.getName());}}