第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > 获取文件夹中所有文件的文件名[重复]

获取文件夹中所有文件的文件名[重复]

时间:2022-03-07 06:53:35

相关推荐

获取文件夹中所有文件的文件名[重复]

本文翻译自: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 aArrayListwith[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.iopackage .首先,您正在处理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 theFileJavaDoc, I see the constructors.在FileJavaDoc中向上滚动,我看到了构造函数。And that's really all I need to be able to create aFileinstance 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 aFileobject, passing the directory path to the constructor.创建一个File对象,将目录路径传递给构造函数。Use thelistFiles()to retrieve an array ofFileobjects 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());}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。