Java check if file is in folder

How to list all files in a directory in Java

In Java, there are many ways to list all files and folders in a directory. You can use either the Files.walk() , Files.list() , or File.listFiles() method to iterate over all the files available in a certain directory.

The Files.walk() is another static method from the NIO API to list all files and sub-directories in a directory. This method throws a NoSuchFileException exception if the folder doesn’t exist. Here is an example that lists all files and sub-directories in a directory called ~/java-runner :

try (StreamPath> paths = Files.walk(Paths.get("~/java-runner")))  // print all files and folders paths.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 

Since it returns a Stream object, you can filter out nested directories and only list regular files like below:

try (StreamPath> paths = Files.walk(Paths.get("~/java-runner")))  // filer out sub-directories ListString> files = paths.filter(x -> Files.isRegularFile(x)) .map(Path::toString) .collect(Collectors.toList()); // print all files files.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner")))  // filer out regular files ListString> folders = paths.filter(x -> Files.isDirectory(x)) .map(Path::toString) .collect(Collectors.toList()); // print all folders folders.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 
try (StreamPath> paths = Files.walk(Paths.get("~/java-runner")))  // keep only `.java` files ListString> javaFiles = paths.map(Path::toString) .filter(x -> x.endsWith(".java")) .collect(Collectors.toList()); // print all files javaFiles.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 

By default, the Stream object returned by Files.walk() recursively walks through the file tree up to an n-level (all nested files and folders). However, you can pass another parameter to Files.walk() to limit the maximum number of directory levels to visit. Here is an example that restricts the directory level to a top-level folder only (level 1):

try (StreamPath> paths = Files.walk(Paths.get("~/java-runner"), 1))  // print all files and folders in the current folder paths.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 

In the above code, the second parameter of Fils.walk() is the maximum number of levels of directories to visit. A value of 0 means that only the starting file is visited, unless denied by the security manager. A value of Integer.MAX_VALUE indicatea that all levels should be traversed.

The Files.list() static method from NIO API provides the simplest way to list the names of all files and folders in a given directory:

try (StreamPath> paths = Files.list(Paths.get("~/java-runner")))  // print all files and folders paths.forEach(System.out::println); > catch (IOException ex)  ex.printStackTrace(); > 

The Files.list() method returns a lazily populated Stream of entries in the directory. So you can apply all the above filters for Files.walk() on the stream.

In old Java versions (JDK 6 and below), the File.listFiles() method is available to list all files and nested folders in a directory. Here is an example that uses File.listFiles() to print all files and folders in the given directory:

File folder = new File("~/java-runner"); // list all files for (File file : folder.listFiles())  System.out.println(file); > 
File folder = new File("~/java-runner"); // list all regular files for (File file : folder.listFiles())  if (file.isFile())  System.out.println(file); > > 
File folder = new File("~/java-runner"); // list all sub-directories for (File file : folder.listFiles())  if (file.isDirectory())  System.out.println(file); > > 
public void listFilesRecursive(File folder)  for (final File file : folder.listFiles())  if (file.isDirectory())  // uncomment this to list folders too // System.out.println(file); listFilesRecursive(file); > else  System.out.println(file); > > > // list files recursively File folder = new File("~/java-runner"); listFilesRecursive(folder); 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Checking a File or Directory

You have a Path instance representing a file or directory, but does that file exist on the file system? Is it readable? Writable? Executable?

Verifying the Existence of a File or Directory

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists, or does not exist. You can do so with the exists(Path, LinkOption. ) and the notExists(Path, LinkOption. ) methods. Note that !Files.exists(path) is not equivalent to Files.notExists(path) . When you are testing a file’s existence, three results are possible:

  • The file is verified to exist.
  • The file is verified to not exist.
  • The file’s status is unknown. This result can occur when the program does not have access to the file.

If both exists and notExists return false , the existence of the file cannot be verified.

Checking File Accessibility

To verify that the program can access a file as needed, you can use the isReadable(Path) , isWritable(Path) , and isExecutable(Path) methods.

The following code snippet verifies that a particular file exists and that the program has the ability to execute the file.

Path file = . ; boolean isRegularExecutableFile = Files.isRegularFile(file) & Files.isReadable(file) & Files.isExecutable(file);

Note: Once any of these methods completes, there is no guarantee that the file can be accessed. A common security flaw in many applications is to perform a check and then access the file. For more information, use your favorite search engine to look up TOCTTOU (pronounced TOCK-too).

Checking Whether Two Paths Locate the Same File

When you have a file system that uses symbolic links, it is possible to have two different paths that locate the same file. The isSameFile(Path, Path) method compares two paths to determine if they locate the same file on the file system. For example:

Path p1 = . ; Path p2 = . ; if (Files.isSameFile(p1, p2)) < // Logic when the paths locate the same file >

Источник

How to check if a file or folder exists in Java

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

In Java, we can use Files.exists(pathToFileOrDirectory) to test if a file or a folder exists.

Syntax

Files.exists(pathToFileOrDirectory) 

This method returns true if the file is present; otherwise, it returns false . If the file is a symbolic link a file which is a link to another target file , this method returns true only if the target file is present. Otherwise, it returns false .

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class Main
public static void checkFilePresent(Path path)
if (Files.exists(path))
if (Files.isDirectory(path))
System.out.println("It is a directory");
> else if (Files.isRegularFile(path))
System.out.println("File test.txt present");
>
> else
System.out.println("File not found ");
>
>
public static void main( String args[] )
String currentDir = "./";
String fileName1 = "test.txt";
Path path = Paths.get(currentDir + fileName1);
checkFilePresent(path);
String fileName2 = "write.txt";
path = Paths.get(currentDir + fileName2);
checkFilePresent(path);
>
>

Источник

Читайте также:  Python get image width
Оцените статью