I would like to ask you : How i can make a program which is making a simple "like filter" to search files by user input. Like when a user input from a console:
*fileName.txt it searches all files which is containing fileName and the asteriks shows that it can have some words before "fileName".
Here are some examples:
User input from console:
*text.txt -> matches all files containing text.txt
fileName*.txt - > matches all files containing fileName and it can contains words after "fileName".
file*Name.txt ->matches all files containig file and Name and it can have some words between them.
I know it must be with regex , but i do not know what regex should i use. So can you tell me what patterns should i use .
Thank you in advanced!
Here is my code for now searching a files:
public void FilterFile(String directory, String fileToSearch)
{
File filePath = null;
if (directory != null)
{
File filePath = new File(directory); \\ reads Directory
FilenameFilter fnf = new FilenameFilter()
{
#Override
public boolean accept(File dir, String name)
{
if (name != null)
{
if(pattern.matcher(name).matches()) // pattern that should use for matching and filtering files by user input
{
return true;
}
return false;
}
};
File[] files = filePath.listFiles(fnf);
if (files != null)
{
for (File file : files)
{
System.out.println(file.getAbsolutePath() + " found");
}
}
}
}
Try
(fileName)\w+.txt
for fileName*.txt
(file)\w+(Name).txt
for file*Name.txt
and
\w+(text).txt for *text.txt
Related
Hello I'm trying to get with numerical order all files that exist in a folder.
First i check a folder(main folder) the sub-folders that contained in. After that, for each sub-folder I'm getting the names of the files that exist in.
I wrote a code that does this job for me but when i print (the names of the files of a sub-folder) I'm not getting them with the correct order.(numerical).
For example i have my main Folder called 'test', in there exist 3 sub-folder named Sub1, Sub2, Sub3
FOLDER Test *contains* [ FOLDER SUB1 || FOLDER SUB2 || FOLDER SUB3 ]
Each sub-Fodler have files with names (1.txt , 2.txt ,.....,15.txt,16.txt,...,22.txt,...etc)
This code does this job... but...
import java.io.File;
import java.io.FileFilter;
public class Main {
public static void main(String[] args) {
File file = new File("C:\\test");
File[] files = file.listFiles(new FileFilter() {
public boolean accept(File f) {
String name=f.getName(); //read every subfodler name
System.out.println(name);
File folder = new File("C:\\test\\"+name); //for each subfolder
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
//print the names of files that included
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
return f.isDirectory();
}});
}
}
but the output is like that...
Folder1
File 1.txt
File 10.txt
File 11.txt
File 12.txt
File 13.txt
File 14.txt
File 2.txt
File 3.txt
File 4.txt
File 5.txt
File 6.txt
File 7.txt
File 8.txt
File 9.txt
Folder2
............... same order as Folder1 ... etc
How i could taking the file names with numerical order so the output that i will get will be like that:
Folder1
File 1.txt
File 2.txt
File 3.txt
File 4.txt
File 5.txt
File 6.txt
File 7.txt
File 8.txt
File 9.txt
File 10.txt
File 11.txt
File 12.txt
File 13.txt
File 14.txt
Once you have the files in a list or array you can sort them using Collections.sort() or Arrays.sort() and a custom comparator like in this example
java.io.File is an obsolete class. It was replaced years ago by Path and other classes in the java.nio.file package, like Files and Paths.
You should not use a filter to perform any actions other than filtering. Yes, it works, but you’re relying on side effects instead of the intended functionality.
For comparing the numeric part of a filename, you will need to write your own Comparator:
Path root = Paths.get("C:\\test");
Pattern numericFileNamePattern = Pattern.compile(".*[^0-9]([0-9]+)\\.[^.]+");
Comparator<Path> byNumber = (p1, p2) -> {
String name1 = p1.getFileName().toString();
String name2 = p2.getFileName().toString();
Matcher matcher = numericFileNamePattern.matcher(name1);
if (matcher.matches()) {
String digits1 = matcher.group(1);
String withoutDigits1 = matcher.replaceFirst("");
matcher.reset(name2);
if (matcher.matches()) {
String digits2 = matcher.group(1);
String withoutDigits2 = matcher.replaceFirst("");
if (withoutDigits1.equals(withoutDigits2)) {
long num1 = Long.parseLong(digits1);
long num2 = Long.parseLong(digits2);
return Long.compare(num1, num2);
}
}
}
return p1.compareTo(p2);
};
try (DirectoryStream<Path> dir = Files.newDirectoryStream(root)) {
for (Path child : dir) {
if (Files.isDirectory(child)) {
try (Stream<Path> listing = Files.list(child)) {
Path[] files = listing.filter(f -> Files.isRegularFile(f))
.sorted(byNumber).toArray(Path[]::new);
for (Path file : files) {
System.out.println(file);
}
}
}
}
}
I'm writing a program that does various data analysis functions for use with Excel.
I need a way of returning file names of documents so I can search through them and find the ones I want.
I need to be able to take a string, saved as a variable, and use it to return the name of every document in a folder whose file name contains that string.
This will be used to sift through pre-categorized sections of data. Ideally I would save those documents' file names in a string array for later use within other functions.
private List<String> searchForFileNameContainingSubstring( String substring )
{
//This is assuming you pass in the substring from input.
File file = new File("C:/Users/example/Desktop"); //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.
}
Using this method, you could pass in the input from the user as the string you want the filename to contain. The only other thing you need to change is where you want in your directory to start searching for files, and this program only looks in that directory.
You could further look recursively within other directories from the starting point, but I won't add that functionality here. You should definitely look into it though.
This also assumes that you are looking for everything within the directory, including other folders and not just files.
You can get the list of all the files in a directory and then store them in an array. Next, using the java.io.File.getName() method, you can get the names of the files. Now you can simply use the .indexOf() method to check whether the string is a substring of the file name. I assume that all the items in the directory of concern are files and not sub directories.
public static void main(String[] args) throws IOException {
File[] files = new File("X:/").listFiles(); //X is the directory
String s <--- the string you want to check filenames with
for(File f : files){
if(f.getName().toLowerCase().indexOf(s.toLowerCase()) != -1)
System.out.println(f.getName());
}
}
This should display the names of all those files in the directory X:\ whose names include the String s.
References
This question: How do I iterate through the files in a directory in Java?
The java.io.File.getName() method
Statutory edit info
I have edited this answer simply to replace the previous algorithm, for checking the existence of a substring in a string, with the one that is currently used in the code above.
Here is an answer to search the file recursively??
String name; //to hold the search file name
public String listFolder(File dir) {
int flag;
File[] subDirs = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
System.out.println("File of Directory: " + dir.getAbsolutePath());
flag = Listfile(dir);
if (flag == 0) {
System.out.println("File Found in THe Directory: " + dir.getAbsolutePath());
Speak("File Found in THe Directory: !!" + dir.getAbsolutePath());
return dir.getAbsolutePath();
}
for (File folder : subDirs) {
listFolder(folder);
}
return null;
}
private int Listfile(File dir) {
boolean ch = false;
File[] files = dir.listFiles();
for (File file : files) {
Listfile(file);
if (file.getName().indexOf(name.toLowerCase()) != -1) {//check all in lower case
System.out.println(name + "Found Sucessfully!!");
ch = true;
}
}
if (ch) {
return 1;
} else {
return 0;
}
}
I have a directory structure of the form:
base_directory / level_one_a, level_one_b, level_one_c /
then within all those directories in level_one_x are a multitude of subsequent directories, i.e.
/ level_one_a_1,level_one_a_2,level_one_a_3...
and so on for level_one_b & level_one_c
then inside of level_one_a_1 we have more still, i.e. level_one_a_1_I,level_one_a_1_II,level_one_a_1_III,level_one_a_1_IV...
Then finally inside of level_one_a_1_IV, and all those on the same level, are the files I want to operate on.
I guess a shorter way to say that would be start/one/two/three/*files*
There are many many files and I want to process them all with a simple java program I wrote:
try
{
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
Document doc = Jsoup.parse(everything);
String link = doc.select("block.full_text").text();
System.out.println(link);
}
finally
{
br.close();
}
it uses jsoup
I'd like to construct this script such that the program can navigate this directory structure autonomously and grab each file then process it with that script, using buffered reader and file reader I guess, how can I facilitate that? I tried implementing this solution but I couldn't get it to work.
Ideally I want to output each file it processes with a unique name, i.e. is the file is named 00001.txt it might save it as 00001_output.txt but, that's a horse of a different colour
Just use java.io.File and its method listFiles.
See javadoc File API
Similar question on SO was posted here:
Recursively list files in Java
You can achieve this also by using the Java NIO 2 API.
public class ProcessFiles extends SimpleFileVisitor<Path> {
static final String OUT_FORMAT = "%-17s: %s%n";
static final int MAX_DEPTH = 4;
static final Path baseDirectory = Paths.get("R:/base_directory");
public static void main(String[] args) throws IOException {
Set<FileVisitOption> visitOptions = new HashSet<>();
visitOptions.add(FileVisitOption.FOLLOW_LINKS);
Files.walkFileTree(baseDirectory, visitOptions, MAX_DEPTH,
new ProcessFiles()
);
}
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
if (file.getNameCount() <= MAX_DEPTH) {
System.out.printf(OUT_FORMAT, "skip wrong level", file);
return FileVisitResult.SKIP_SUBTREE;
} else {
// add probably a file name check
System.out.printf(OUT_FORMAT, "process file", file);
return CONTINUE;
}
}
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attr) {
if (dir.getNameCount() < MAX_DEPTH) {
System.out.printf(OUT_FORMAT, "walk into dir", dir);
return CONTINUE;
}
if (dir.getName(MAX_DEPTH - 1).toString().equals("level_one_a_1_IV")) {
System.out.printf(OUT_FORMAT, "destination dir", dir);
return CONTINUE;
} else {
System.out.printf(OUT_FORMAT, "skip dir name", dir);
return FileVisitResult.SKIP_SUBTREE;
}
}
}
assuming following directory/file structure
base_directory
base_directory/base_directory.file
base_directory/level_one_a
base_directory/level_one_a/level_one_a.file
base_directory/level_one_a/level_one_a_1
base_directory/level_one_a/level_one_a_1/level_one_a_1.file
base_directory/level_one_a/level_one_a_1/level_one_a_1_I
base_directory/level_one_a/level_one_a_1/level_one_a_1_I/level_one_a_1_I.file
base_directory/level_one_a/level_one_a_1/level_one_a_1_II
base_directory/level_one_a/level_one_a_1/level_one_a_1_II/level_one_a_1_II.file
base_directory/level_one_a/level_one_a_1/level_one_a_1_III
base_directory/level_one_a/level_one_a_1/level_one_a_1_III/level_one_a_1_III.file
base_directory/level_one_a/level_one_a_1/level_one_a_1_IV
base_directory/level_one_a/level_one_a_1/level_one_a_1_IV/level_one_a_1_IV.file
base_directory/someother_a
base_directory/someother_a/someother_a.file
base_directory/someother_a/someother_a_1
base_directory/someother_a/someother_a_1/someother_a_1.file
base_directory/someother_a/someother_a_1/someother_a_1_I
base_directory/someother_a/someother_a_1/someother_a_1_I/someother_a_1_I.file
base_directory/someother_a/someother_a_1/someother_a_1_II
base_directory/someother_a/someother_a_1/someother_a_1_II/someother_a_1_II.file
base_directory/someother_a/someother_a_1/someother_a_1_III
base_directory/someother_a/someother_a_1/someother_a_1_III/someother_a_1_III.file
base_directory/someother_a/someother_a_1/someother_a_1_IV
base_directory/someother_a/someother_a_1/someother_a_1_IV/someother_a_1_IV.file
you would get following output (for demonstration)
walk into dir : R:\base_directory
skip wrong level : R:\base_directory\base_directory.file
walk into dir : R:\base_directory\level_one_a
skip wrong level : R:\base_directory\level_one_a\level_one_a.file
walk into dir : R:\base_directory\level_one_a\level_one_a_1
skip wrong level : R:\base_directory\level_one_a\level_one_a_1\level_one_a_1.file
skip dir name : R:\base_directory\level_one_a\level_one_a_1\level_one_a_1_I
skip dir name : R:\base_directory\level_one_a\level_one_a_1\level_one_a_1_II
skip dir name : R:\base_directory\level_one_a\level_one_a_1\level_one_a_1_III
destination dir : R:\base_directory\level_one_a\level_one_a_1\level_one_a_1_IV
process file : R:\base_directory\level_one_a\level_one_a_1\level_one_a_1_IV\level_one_a_1_IV.file
walk into dir : R:\base_directory\someother_a
skip wrong level : R:\base_directory\someother_a\someother_a.file
walk into dir : R:\base_directory\someother_a\someother_a_1
skip wrong level : R:\base_directory\someother_a\someother_a_1\someother_a_1.file
skip dir name : R:\base_directory\someother_a\someother_a_1\someother_a_1_I
skip dir name : R:\base_directory\someother_a\someother_a_1\someother_a_1_II
skip dir name : R:\base_directory\someother_a\someother_a_1\someother_a_1_III
skip dir name : R:\base_directory\someother_a\someother_a_1\someother_a_1_IV
some links to the Oralce tutorial for further reading
Walking the File Tree
Finding Files
I need to create a program which gets its input from a file. What do I need to use in order to automatically find the current path and then search for the input file?
Example: I place my main file in C:/*pathname*/ and my input file name is INPUT.txt. How can I make my program automatically find the C:/*pathname*/INPUT.txt path to get its input?
You can use recursion in this case, to find your file. You start the searching process in the current/given directory, by checking if your current file matches the given file name. If you find a directory, you continue the recursion searching process in this directory.
private static final File findFile(final String rootFilePath, final String fileToBeFound) {
File rootFile = new File(rootFilePath);
File[] subFiles = rootFile.listFiles();
for (File file : subFiles != null ? subFiles : new File[] {}) {
if (file.getAbsolutePath().endsWith(fileToBeFound)) {
return file;
} else if (file.isDirectory()) {
File f = findFile(file.getAbsolutePath(), fileToBeFound);
if (f != null) {
return f;
}
}
}
return null; // null returned in case your file is not found
}
public static void main(final String[] args){
File fileToBeFound = findFile("C:\\", "INPUT.txt"); // search for the file in all the C drive
System.out.println(fileToBeFound != null ? fileToBeFound.getAbsolutePath() : "Not found");
//you can also use your current workspace directory, if you're sure the file is there
fileToBeFound = findFile(new File(".").getAbsolutePath() , "INPUT.txt");
System.out.println(fileToBeFound != null ? fileToBeFound.getAbsolutePath() : "Not found");
}
I'm working with some code and I want it to behave differently depending on the folder name that the file is in. I don't need the absolute path just the final folder. Everything that I have seen so far is using a absolute path that is specified in the file.
This is what you want:
public static String getParentName(File file) {
if(file == null || file.isDirectory()) {
return null;
}
String parent = file.getParent();
parent = parent.substring(parent.lastIndexOf("\\") + 1, parent.length());
return parent;
}
Unfortunately there is no pre-provided method that just returns the name of the last folder in the file's path, so you have to do some String manipulation to get it.
I think java.io.File.getParent() is what you are looking for:
import java.io.File;
public class Demo {
public static void main(String[] args) {
File f = null;
String parent="not found";
f = new File("/tmp/test.txt");
parent = f.getParent();
System.out.print("parent name: "+v);
}
}
Try java.io.File.getParentFile() method.
String getFileParentName(File file) {
if (file != null && file.getParentFile() != null) {
return file.getParentFile().getName();
}
return null; // no parent for file
}
There's
String File.getParent()
There's also
File File.getParentFile()
I don't know what the return in terms of being absolute or relative, but if it's absolute you can always find the last (or second to last, depending) instance of the "\" character (remember to escape it like this "\\") to denote where the lowest folder level is.
For example, if the function returned:
"C:\Users\YourName" is where you'd get the last occurance of "\", and all characters after it would be the folder you want
"C:\Users\YourName\" is where you'd get the second to last occurance of "\", and all characters between that and the last "\" would be the folder you're looking for.
Java File API:
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
String path = "/abc/def"; // path to the directory
try
{
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles)
{
if(file.isDirectory())
{
switch(file.getName)
{
case "folder1" : //do something
break
case "folder2" : //do something else
break
}
}
}
}
catch(Exception e)
{
System.out.println("Directory not Found");
}