Finding file path java

Finding Files

If you have ever used a shell script, you have most likely used pattern matching to locate files. In fact, you have probably used it extensively. If you haven’t used it, pattern matching uses special characters to create a pattern and then file names can be compared against that pattern. For example, in most shell scripts, the asterisk, * , matches any number of characters. For example, the following command lists all the files in the current directory that end in .html :

The java.nio.file package provides programmatic support for this useful feature. Each file system implementation provides a PathMatcher . You can retrieve a file system’s PathMatcher by using the getPathMatcher(String) method in the FileSystem class. The following code snippet fetches the path matcher for the default file system:

String pattern = . ; PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);

The string argument passed to getPathMatcher specifies the syntax flavor and the pattern to be matched. This example specifies glob syntax. If you are unfamiliar with glob syntax, see What is a Glob.

Glob syntax is easy to use and flexible but, if you prefer, you can also use regular expressions, or regex, syntax. For further information about regex, see the Regular Expressions lesson. Some file system implementations might support other syntaxes.

If you want to use some other form of string-based pattern matching, you can create your own PathMatcher class. The examples in this page use glob syntax.

Once you have created your PathMatcher instance, you are ready to match files against it. The PathMatcher interface has a single method, matches , that takes a Path argument and returns a boolean: It either matches the pattern, or it does not. The following code snippet looks for files that end in .java or .class and prints those files to standard output:

Читайте также:  Оформление стиля css html

PathMatcher matcher = FileSystems.getDefault().getPathMatcher(«glob:*.»); Path filename = . ; if (matcher.matches(filename))

Recursive Pattern Matching

Searching for files that match a particular pattern goes hand-in-hand with walking a file tree. How many times do you know a file is somewhere on the file system, but where? Or perhaps you need to find all files in a file tree that have a particular file extension.

The Find example does precisely that. Find is similar to the UNIX find utility, but has pared down functionally. You can extend this example to include other functionality. For example, the find utility supports the -prune flag to exclude an entire subtree from the search. You could implement that functionality by returning SKIP_SUBTREE in the preVisitDirectory method. To implement the -L option, which follows symbolic links, you could use the four-argument walkFileTree method and pass in the FOLLOW_LINKS enum (but make sure that you test for circular links in the visitFile method).

To run the Find application, use the following format:

The pattern is placed inside quotation marks so any wildcards are not interpreted by the shell. For example:

Here is the source code for the Find example:

/** * Sample code that finds files that match the specified glob pattern. * For more information on what constitutes a glob pattern, see * https://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob * * The file or directories that match the pattern are printed to * standard out. The number of matches is also printed. * * When executing this application, you must put the glob pattern * in quotes, so the shell will not expand any wild cards: * java Find . -name "*.java" */ import java.io.*; import java.nio.file.*; import java.nio.file.attribute.*; import static java.nio.file.FileVisitResult.*; import static java.nio.file.FileVisitOption.*; import java.util.*; public class Find < public static class Finder extends SimpleFileVisitor < private final PathMatcher matcher; private int numMatches = 0; Finder(String pattern) < matcher = FileSystems.getDefault() .getPathMatcher("glob:" + pattern); >// Compares the glob pattern against // the file or directory name. void find(Path file) < Path name = file.getFileName(); if (name != null && matcher.matches(name)) < numMatches++; System.out.println(file); >> // Prints the total number of // matches to standard out. void done() < System.out.println("Matched: " + numMatches); >// Invoke the pattern matching // method on each file. @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) < find(file); return CONTINUE; >// Invoke the pattern matching // method on each directory. @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) < find(dir); return CONTINUE; >@Override public FileVisitResult visitFileFailed(Path file, IOException exc) < System.err.println(exc); return CONTINUE; >> static void usage() < System.err.println("java Find " + " -name \"\""); System.exit(-1); > public static void main(String[] args) throws IOException < if (args.length < 3 || !args[1].equals("-name")) usage(); Path startingDir = Paths.get(args[0]); String pattern = args[2]; Finder finder = new Finder(pattern); Files.walkFileTree(startingDir, finder); finder.done(); >>

Recursively walking a file tree is covered in Walking the File Tree.

Источник

Get file full path in java

When I pass File file to a method I’m trying to get its full path like file.getAbsolutePath(); I always get the same result no matter which one I use either absolute or canonical path PATH_TO_MY_WORKSPACE/projectName/filename and it is not there, how can I get exact location of the file? Thank you DETAILS: Here is some code and this solutions(its bad but its working):

 private static void doSomethingToDirectory(File factDir) throws IOException < File[] dirContents = factDir.listFiles(); if(factDir.isDirectory() && dirContents.length >0) < for (int i = 0; i < dirContents.length; i++) < for (String str : dirContents[i].list()) < if(str.equals(TEMP_COMPARE_FILE))< process(new File(dirContents[i].getAbsolutePath() + "\\" + str)); >> > > > 

I’m looping trough directories where factDir is src/main , I’m seeking toBeProcessed.txt files only that is TEMP_COMPARE_FILE value and I’m sending them to process method which reads the file and does processing of it. If someone could better solution I’d be greatful

It sounds like to me you are just instantiating a File object, but that doesn’t actually create anything on disk until you write to the file using a Writer or an Outputstream, or call createNewFile()

2 Answers 2

This quote from the Javadoc might be helpful:

A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir , and is typically the directory in which the Java virtual machine was invoked.

I interpret this so that if you create your File object with new File(«filename») where filename is a relative path, that path will not be converted into an absolute path even by a call to file.getAbsolutePath() .

Update: now that you posted code, I can think of some ways to improve it:

  • you could use a FilenameFilter to find the desired files,
  • note that list and listFiles return null for non-directory objects, so we need an extra check for that,
  • you could also use listFiles() again in the inner loop, thus avoiding the need to create new File objects with hand-assembled paths. (Btw note that appending \\ manually to the path is not portable; the proper way would be to use File.separator ).
private static void doSomethingToDirectory(File factDir) throws IOException < if (factDir.isDirectory()) < for (File file : factDir.listFiles()) < if (file.isDirectory()) < for (File child : file.listFiles(new MyFilter())) < process(child); >> > > > class MyFilter implements FilenameFilter < public boolean accept(File dir, String name) < return name.equals(TEMP_COMPARE_FILE); >> 

Note that this code mimics the behaviour of your original piece of code as much as I understood it; most notably, it finds the files with the proper name only in the direct subdirectories of factDir , nonrecursively.

Источник

Get the filePath from Filename using Java

You mean you have the name of a file and want to get the path? What about if there are many files named like this?

yes. i wanted to know if there is any oneliner code which will get the path of a already xisting file. I think i will have to search through the directories and then list the files.

5 Answers 5

Path p = Paths.get(yourFileNameUri); Path folder = p.getParent(); 

Look at the methods in the java.io.File class:

File file = new File("yourfileName"); String path = file.getAbsolutePath(); 

i already have a file name ‘file1.txt’ and is stored in D:\\IM\\EclipseWorkspaces\\runtime-EclipseApplication\\Proj\\Software and If a do File file = new File(«file1.txt»); and get the file.getAbsolutePath, it gives me D:\\IM\\EclipseVersions\\EclipseSDK3_7\\file1.txt. which is not i want.

I’m not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:

System.out.println("File path: " + new File("Your file name").getAbsolutePath()); 

The File class has several more methods you might find useful.

Correct solution with «File» class to get the directory — the «path» of the file:

String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent(); 
path = "C:\\Temp\\your directory" 
FileSystems.getDefault().getPath(new String()).toAbsolutePath(); 
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent() 

This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.

Источник

Оцените статью