【发布时间】:2013-05-06 19:23:12
【问题描述】:
这是我必须做的,但我不知道从哪里开始:
编写一个程序,让您从 指定的目录。图片随后显示在窗口中,如 如下:
- a) 目录和图像之间的时间间隔(以秒为单位)是在程序启动时根据 文件中的信息,
- b) 图片以其原始尺寸显示,
- c) 将图像调整为框架
我知道非常基本的问题,但刚刚开始使用 Java。 是否有某种功能可以为我提供文件夹中所有项目的名称?
【问题讨论】:
这是我必须做的,但我不知道从哪里开始:
编写一个程序,让您从 指定的目录。图片随后显示在窗口中,如 如下:
- a) 目录和图像之间的时间间隔(以秒为单位)是在程序启动时根据 文件中的信息,
- b) 图片以其原始尺寸显示,
- c) 将图像调整为框架
我知道非常基本的问题,但刚刚开始使用 Java。 是否有某种功能可以为我提供文件夹中所有项目的名称?
【问题讨论】:
如果您想为目录中的所有文件创建文件对象,请使用:
new File("path/to/directory").listFiles();
如果您只想使用名称
new File("path/to/directory").list();
【讨论】:
如果你只想要图片文件,你可以使用File.listFiles( FileFilter filter ):
File[] files = new File( myPath ).listFiles(
new FileFilter() {
boolean accept(File pathname) {
String path = pathname.getPath();
return ( path.endsWith(".gif")
|| path.endsWith(".jpg")
|| ... );
}
});
【讨论】:
我假设您想要获取一个目录及其所有子目录中的所有图像。给你:
//Load all the files from a folder.
File folder = new File(folderPathString);
readDirectory(folder);
public static void readDirectory(File dir) throws IOException
{
File[] folder = dir.listFiles();//lists all the files in a particular folder, includes directories
for (int i = 0; i < folder.length; i++)
{
File file = folder[i];
if (file.isFile() && (file.getName().endsWith(".gif") || file.getName().endsWith(".jpg"))
{
read(file);
}
else if (file.isDirectory())
{
readDirectory(file);
}
}
}
public static void read(File input) throws IOException
{
//Do whatever you need to do with the file
}
【讨论】:
如果你可以使用JDK 7,那么推荐的方式(如果我可以说的话)是:
public static void main(String[] args) throws IOException {
Path dir = Paths.get("c:/some_dir");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{gif,png,jpg}")) {
for (Path entry: stream) {
System.out.println(entry);
}
}
}
它更高效,因为您获得了不一定包含所有条目的迭代器。
【讨论】: