Java find file linux

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:

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).

Читайте также:  Linux поменять mac адрес

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.

Источник

Java linux command to see path file

In case yes, you can use the result of that command as input for your command: Or, (this is more readable but it does not always work): Solution 2: This should run the first .jar file found: Solution 1: You can use : From : Solution 2: I found another command : Solution 3: If you want to tell the command on Linux to return information about the command, and to resolve all symbolic links while doing so, then use with its option: To resolve all links to get the final absolute path of a command, use : Solution: Different distributions put some files in different places. Who’s the owner of the file etc? Please do/check the following: Check for the file access permissions Always use absolute path (with ‘/’ in front)

Creating a file from a file path that can be opened in Linux

There is nothing specific to Linux.

Java is platform independent language and no special case is required.

Edit : My bad that I misunderstood it completely. Did you check with the file permissions? Who’s the owner of the file etc?

Please do/check the following:

  1. Check for the file access permissions
  2. Always use absolute path (with ‘/’ in front)
  3. For home directory, try using System.getProperty(«user.home») like —
File userHomeDir = new File(System.getProperty("user.home")); File fileToRead = new File(userHomeDir , "Desktop/out.txt"); 

The above should be able to give you a definite solution. Else, you might be over looking something, which I’m not sure.

Читайте также:  404 Not Found

So I feel silly. Turns out there was just a space at the end on my file path every time I imported it. I had tried putting in a trim statement but then I was a stupid stupid head and didn’t set filePath = file.Path.trim(). Sorry for the trouble guys!

Java File Path Windows/Linux, It is good if the file path is visible somewhere. If user can’t see the path then simpler solution is to use slash ‘/’ everywhere. – jsosnowski.

Linux: How to get path to file in nested folder

Can you find the jar-file, using a find command?

In case yes, you can use the result of that command as input for your command:

Or, (this is more readable but it does not always work):

This should run the first .jar file found:

java -jar `ls rootfolder/**/*.jar | head -1` 

Guide to the Linux find Command, The path argument specifies one or more directories to search. The default is the current working directory. The expression argument is what

How to find the final excutable file path using file command?

$ readlink -f -- "$(which awk)" /usr/bin/gawk 

-f, —canonicalize canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist

I found another command realpath :

realpath -- "$(which awk)" #Output: /usr/bin/gawk 

If you want to tell the file command on Linux to return information about the awk command, and to resolve all symbolic links while doing so, then use file with its -L option:

$ file -L -- "$(command -v awk)" /bin/awk: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=b863ebf57d3cc33d8e7fed3be0e0b5d235489b46, for GNU/Linux 3.2.0, stripped 

To resolve all links to get the final absolute path of a command, use readlink -e :

$ readlink -e -- "$(command -v awk)" /usr/bin/gawk 

Finding the absolute path of a running jar in linux, /etc/runit/artifacts/osd-service-api is an absolute path, not a relative one. · No it is a relative path, i couldnot find it from the root folder

How to find file in path in Void linux

Different distributions put some files in different places. That’s normal, just go with whatever you find in void-linux and don’t worry if its in a different place than you are expecting to see it compared to another distribution . The only caveat would be if you suddenly find it in a real oddball location like /tmp or your home directory.

If its a standard utility installed by void-linux and its not in /usr/sbin, /bin (or their sub-directories) then question its authenticity and ASK about it before executing it.

How to Add a Directory to Your $PATH in Linux, The output is a list of colon ( : ) delimited file system locations. The shell searches from left to right through the path, checking each file

Источник

Java Files.find examples

The Files.find API is available since Java 8. It searches or finds files from a file tree quickly.

In the old days, we always use an error-prone recursive loop to walk a file tree. This Java 8 Files.find can save you a lot of time.

1. Files.find() Signature

Review the Files.find() signature.

 public static Stream find(Path start, int maxDepth, BiPredicate matcher, FileVisitOption. options) throws IOException 
  • The path , starting file or folder.
  • The maxDepth defined the maximum number of directory levels to search. If we put 1 , which means the search for top-level or root folder only, ignore all its subfolders; If we want to search for all folder levels, put Integer.MAX_VALUE .
  • The BiPredicate is for condition checking or filtering.
  • The FileVisitOption tells if we want to follow symbolic links, default is no. We can put FileVisitOption.FOLLOW_LINKS to follow symbolic links.
Читайте также:  Kali linux скинуть пароль

2. Find files by filename

This example uses Files.find() to find files that matched filename google.png , starting from the folder C:\\test , and included all levels of its subfolders.

 package com.mkyong.io.api; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FileFindExample1 < public static void main(String[] args) throws IOException < Path path = Paths.get("C:\\test"); Listresult = findByFileName(path, "google.png"); result.forEach(x -> System.out.println(x)); > public static List findByFileName(Path path, String fileName) throws IOException < Listresult; try (Stream pathStream = Files.find(path, Integer.MAX_VALUE, (p, basicFileAttributes) -> p.getFileName().toString().equalsIgnoreCase(fileName)) ) < result = pathStream.collect(Collectors.toList()); >return result; > > 

We also can use Files APIs to check the path further.

 try (Stream pathStream = Files.find(path, Integer.MAX_VALUE, (p, basicFileAttributes) -> < // if directory or no-read permission, ignore if(Files.isDirectory(p) || !Files.isReadable(p))< return false; >return p.getFileName().toString().equalsIgnoreCase(fileName); >) ) 

3. Find files by file size

This example uses Files.find() to find files containing file size greater or equals 100MB.

 package com.mkyong.io.api; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FileFindExample2 < public static void main(String[] args) throws IOException < Path path = Paths.get("C:\\Users\\mkyong\\Downloads"); long fileSize = 1024 * 1024 * 100; // 100M Listresult = findByFileSize(path, fileSize); for (Path p : result) < System.out.println(String.format("%-40s [fileSize]: %,d", p, Files.size(p))); >> public static List findByFileSize(Path path, long fileSize) throws IOException < Listresult; try (Stream pathStream = Files.find(path, Integer.MAX_VALUE, (p, basicFileAttributes) -> < try < if (Files.isDirectory(p)) < // ignore directory return false; >return Files.size(p) >= fileSize; > catch (IOException e) < System.err.println("Unable to get the file size of path : " + path); >return false; > )) < result = pathStream.collect(Collectors.toList()); >return result; > > 
 C:\Users\mkyong\Downloads\hello.mp4 [fileSize]: 4,796,543,886 C:\Users\mkyong\Downloads\java.mp4.bk [fileSize]: 5,502,785,778 C:\Users\mkyong\Downloads\ubuntu-20.04.1-desktop-amd64.iso [fileSize]: 2,785,017,856 #. 

4. Find files by last modified time

This example uses File.find() to find files containing last modified time equals or after yesterday.

 package com.mkyong.io.api; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FileFindExample3 < private static DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); public static void main(String[] args) throws IOException < // find files, LastModifiedTime from yesterday and above Listresult = findByLastModifiedTime( Paths.get("C:\\test"), Instant.now().minus(1, ChronoUnit.DAYS)); for (Path p : result) < // formatting. BasicFileAttributes attrs = Files.readAttributes(p, BasicFileAttributes.class); FileTime time = attrs.lastModifiedTime(); LocalDateTime localDateTime = time.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDateTime(); System.out.println(String.format("%-40s [%s]", p, localDateTime.format(DATE_FORMATTER))); >> public static List findByLastModifiedTime(Path path, Instant instant) throws IOException < Listresult; try (Stream pathStream = Files.find(path, Integer.MAX_VALUE, (p, basicFileAttributes) -> < if(Files.isDirectory(p) || !Files.isReadable(p))< return false; >FileTime fileTime = basicFileAttributes.lastModifiedTime(); // negative if less, positive if greater // 1 means fileTime equals or after the provided instant argument // -1 means fileTime before the provided instant argument int i = fileTime.toInstant().compareTo(instant); return i > 0; > )) < result = pathStream.collect(Collectors.toList()); >return result; > > 

Output samples and assume today is 02/12/2020

 C:\test\a.txt [02/12/2020 13:01:20] C:\test\b.txt [01/12/2020 12:11:21] #. 

Источник

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