A function that will give the names of all the items in the folder

Here is what I need to do, but I donโ€™t know where to start:

Write a program that allows you to view images (gif, jpg) from the specified directory. Subsequently, the images are displayed in the window, as follows:

  • a) the directory and the time interval between the image (in seconds) is determined at the beginning of the program based on information from the file,
  • b) images are displayed in their original sizes,
  • c) adjust image to frame

I know the simplest question, but just starting with Java. Is there any function that will give me the names of all the items in the folder?

+4
source share
4 answers

If you want to have file objects for all files in a directory, use:

new File("path/to/directory").listFiles(); 

If you just want the names to use

 new File("path/to/directory").list(); 
+6
source

If you only need image files, you can use 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") || ... ); } }); 
+3
source

I assume that you want to get all the images in the directory and in all its subdirectories. Here you are:

  //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 } 
+1
source

If you can use JDK 7, the recommended way (so to speak):

 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); } } } 

This is more efficient because you have an iterator that does not necessarily contain all the records.

+1
source

Source: https://habr.com/ru/post/1480361/


All Articles