I am trying to search files from sd card so i can delete multiple and duplicate files.``
private List<String> searchForFileNameContainingSubstring(String substring)
{
path = Environment.getExternalStorageDirectory().getPath() + "/";
//This is assuming you pass in the substring from input.
File file = new File(path); //Change this to the directory you want to search in.
List<String> filesContainingSubstring = new ArrayList<String>();
if (file.exists() && file.isDirectory())
{
String[] files = file.list(); //get the files in String format.
for (String fileName : files)
{
if (fileName.contains(substring))
filesContainingSubstring.add(fileName);
}
}
for (String fileName : filesContainingSubstring)
{
System.out.println(fileName); //or do other operation
}
return filesContainingSubstring; //return the list of filenames containing substring.
}
How can i scan other sub folders from sdcard/ directories
It only shows results from sdcard directories
You can use Apache Common's FileUtils.listFiles method.
You can search recursively throughout a folder by setting the third parameter as true.
Also, you can target specific file extensions by passing in the second argument a String array as seen below. If you want to target any extensions pass null.
Note: the extensions names do not include '.' it's "jpg" and not ".jpg"
String[] extensions = {"png","jpg"};
Collection images = FileUtils.listFiles(new File("dirPath"),extensions, true);
for (Object obj : images){
File file = (File) obj;
// your code logic
}
Hello I am trying to retrieve the names of all the files of the type .mp3 from a source folder(below)
Below is the code I am using to differentiate the file type and add to the list. However I do not know which parameter I should enter into the directory it should be music folder however I do not know how to represent this.
File dir = new File("");
String[] files = dir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".mp3");
};
});
for(int a = 0; a < files.length; a++)
{
musicList.add(files[a]);
}
Try this.
List<String> result = Files.find(Paths.get("music"), 100,
(p, a) -> p.toString().toLowerCase().endsWith(".mp3"))
.map(path -> path.toString())
.collect(Collectors.toList());
if you are using Servlet :
ServletActionContext.getServletContext().getRealPath("music");
if using Spring :
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("music").getFile());
System.out.println(file.getAbsolutePath());
For javafx see this:
How to target a file (a path to it) in Java/JavaFX
I have a directory full of text files. The naming convention of these files is {userName} + {dayOfYear}
SuperMan201
JamesBond056
JamesBond101
JamesBond093
JamesBondImposter004
SuperMan051
JamesBond057
JamesBond004
I want to search through my files for files that start with Jamesbond. How can I get the first instance of a text file that starts with Jamesbond and not get JamesBondImposter matching my search.
I have a LinkedHashSet that stores the usernames of the users that have text files in the directory. Essentially I want to get the first instance of a JamesBond text file read the file,move the file to another directory, then read subsequent files if they exist; and then move on to the next username in the LinkedList.
If you want to select files from directory take a look at https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FileFilter) and https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FilenameFilter) - just write the filter that will match what you want
Using Apache commons-io (listFiles and iterateFiles methods). Usually the code looks something like this:
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("James*");
File[] files = dir.listFiles(fileFilter);
if(files!=null && files.length > 0)
{
your desired file is files[0]
}
If you're using Java 8, you can do this:
Path dir = Paths.get(fullPathOfDirectory);
Stream<Path> jamesBondFiles = Files.list(dir).filter(path ->
path.getFileName().toString().matches("JamesBond\\d+"));
Iterator<Path> i = jamesBondFiles.iterator();
while (i.hasNext()) {
Path file = i.next();
try (BufferedReader reader = Files.newBufferedReader(file)) {
// Read and process file
}
}
If you're using Java 7, or don't want to use a Stream, you can do:
Path dir = Paths.get(fullPathOfDirectory);
final PathMatcher matcher =
dir.getFileSystem().getPathMatcher("regex:JamesBond\\d+");
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
#Override
public boolean accept(Path path) {
return matcher.matches(path.getFileName());
}
};
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, filter)) {
Charset charset = Charset.defaultCharset();
for (Path file : ds) {
try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
// Read and process file
}
}
}
Is there a Java equivalent for System.IO.Path.Combine() in C#/.NET? Or any code to accomplish this?
This static method combines one or more strings into a path.
Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.
If you're using Java 7 or Java 8, you should strongly consider using java.nio.file.Path; Path.resolve can be used to combine one path with another, or with a string. The Paths helper class is useful too. For example:
Path path = Paths.get("foo", "bar", "baz.txt");
If you need to cater for pre-Java-7 environments, you can use java.io.File, like this:
File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:
public static String combine(String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
In Java 7, you should use resolve:
Path newPath = path.resolve(childPath);
While the NIO2 Path class may seem a bit redundant to File with an unnecessarily different API, it is in fact subtly more elegant and robust.
Note that Paths.get() (as suggested by someone else) doesn't have an overload taking a Path, and doing Paths.get(path.toString(), childPath) is NOT the same thing as resolve(). From the Paths.get() docs:
Note that while this method is very convenient, using it will imply an assumed reference to the default FileSystem and limit the utility of the calling code. Hence it should not be used in library code intended for flexible reuse. A more flexible alternative is to use an existing Path instance as an anchor, such as:
Path dir = ...
Path path = dir.resolve("file");
The sister function to resolve is the excellent relativize:
Path childPath = path.relativize(newPath);
The main answer is to use File objects. However Commons IO does have a class FilenameUtils that can do this kind of thing, such as the concat() method.
platform independent approach (uses File.separator, ie will works depends on operation system where code is running:
java.nio.file.Paths.get(".", "path", "to", "file.txt")
// relative unix path: ./path/to/file.txt
// relative windows path: .\path\to\filee.txt
java.nio.file.Paths.get("/", "path", "to", "file.txt")
// absolute unix path: /path/to/filee.txt
// windows network drive path: \\path\to\file.txt
java.nio.file.Paths.get("C:", "path", "to", "file.txt")
// absolute windows path: C:\path\to\file.txt
I know its a long time since Jon's original answer, but I had a similar requirement to the OP.
By way of extending Jon's solution I came up with the following, which will take one or more path segments takes as many path segments that you can throw at it.
Usage
Path.combine("/Users/beardtwizzle/");
Path.combine("/", "Users", "beardtwizzle");
Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });
Code here for others with a similar problem
public class Path {
public static String combine(String... paths)
{
File file = new File(paths[0]);
for (int i = 1; i < paths.length ; i++) {
file = new File(file, paths[i]);
}
return file.getPath();
}
}
To enhance JodaStephen's answer, Apache Commons IO has FilenameUtils which does this. Example (on Linux):
assert org.apache.commons.io.FilenameUtils.concat("/home/bob", "work\\stuff.log") == "/home/bob/work/stuff.log"
It's platform independent and will produce whatever separators your system needs.
Late to the party perhaps, but I wanted to share my take on this. I prefer not to pull in entire libraries for something like this. Instead, I'm using a Builder pattern and allow conveniently chained append(more) calls. It even allows mixing File and String, and can easily be extended to support Path as well. Furthermore, it automatically handles the different path separators correctly on both Linux, Macintosh, etc.
public class Files {
public static class PathBuilder {
private File file;
private PathBuilder ( File root ) {
file = root;
}
private PathBuilder ( String root ) {
file = new File(root);
}
public PathBuilder append ( File more ) {
file = new File(file, more.getPath()) );
return this;
}
public PathBuilder append ( String more ) {
file = new File(file, more);
return this;
}
public File buildFile () {
return file;
}
}
public static PathBuilder buildPath ( File root ) {
return new PathBuilder(root);
}
public static PathBuilder buildPath ( String root ) {
return new PathBuilder(root);
}
}
Example of usage:
File root = File.listRoots()[0];
String hello = "hello";
String world = "world";
String filename = "warez.lha";
File file = Files.buildPath(root).append(hello).append(world)
.append(filename).buildFile();
String absolute = file.getAbsolutePath();
The resulting absolute will contain something like:
/hello/world/warez.lha
or maybe even:
A:\hello\world\warez.lha
If you do not need more than strings, you can use com.google.common.io.Files
Files.simplifyPath("some/prefix/with//extra///slashes" + "file//name")
to get
"some/prefix/with/extra/slashes/file/name"
Here's a solution which handles multiple path parts and edge conditions:
public static String combinePaths(String ... paths)
{
if ( paths.length == 0)
{
return "";
}
File combined = new File(paths[0]);
int i = 1;
while ( i < paths.length)
{
combined = new File(combined, paths[i]);
++i;
}
return combined.getPath();
}
This also works in Java 8 :
Path file = Paths.get("Some path");
file = Paths.get(file + "Some other path");
This solution offers an interface for joining path fragments from a String[] array. It uses java.io.File.File(String parent, String child):
public static joinPaths(String[] fragments) {
String emptyPath = "";
return buildPath(emptyPath, fragments);
}
private static buildPath(String path, String[] fragments) {
if (path == null || path.isEmpty()) {
path = "";
}
if (fragments == null || fragments.length == 0) {
return "";
}
int pathCurrentSize = path.split("/").length;
int fragmentsLen = fragments.length;
if (pathCurrentSize <= fragmentsLen) {
String newPath = new File(path, fragments[pathCurrentSize - 1]).toString();
path = buildPath(newPath, fragments);
}
return path;
}
Then you can just do:
String[] fragments = {"dir", "anotherDir/", "/filename.txt"};
String path = joinPaths(fragments);
Returns:
"/dir/anotherDir/filename.txt"
Assuming all given paths are absolute paths. you can follow below snippets to merge these paths.
String baseURL = "\\\\host\\testdir\\";
String absoluteFilePath = "\\\\host\\testdir\\Test.txt";;
String mergedPath = Paths.get(baseURL, absoluteFilePath.replaceAll(Matcher.quoteReplacement(baseURL), "")).toString();
output path is \\host\testdir\Test.txt.
This question already has an answer here:
output files from the folder with no extension
(1 answer)
Closed 8 years ago.
Decided to put the question differently, suppose we have a file-test, there is a lot of different files, some of this type indeks.html, kiki.tht, lololo.bin and so on, to get the names of all files in a folder, you can use this code:
File folder = new File("C:\\test\\");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println(listOfFiles[i].getName());
}
}
But how to display only the file name without the extension? Indeks.html looolo.tht not like (just remember files in the lot, there is no duplicate names), and the index and looolo)
String fileName = listOfFiles[i].getName();
int index = fileName.lastIndexOf('.');
if (index >= 0) {
fileName = fileName.substring(0, index);
}
System.out.println(fileName);
String fullName = file.getName();
String nameWithoutExtension = fullName();
int lastDot = fullName.lastIndexOf(".");
if (lastDot >= 0) {
nameWithoutExtension = nameWithoutExtension.substring(0, lastDot);
}
You can get the name of the file and Split the String with
String[] file = filename.Split("\\.");'
file[0] holds the basename, whereas file[1] holds the extension.
Have you tried:
listOfFiles.get(index).getName()
Cheers
Apache Commons IO has a class called FilenameUtils, which offers the method getBaseName(String). Just hand in your file's path for the argument.