Java: automatically detecting input file path - java

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");
}

Related

How do I conditionally get code to loop back to specific point in code in java?

I am creating an application that automatically sorts and organizes files into a database​. I have written my code to read files within the imported folder one at a time, and process them into the DB. However, I am having trouble looping this process, so that I can process files that are nested in any amount of folders within the original folder that the user wants to input.
I simply need to instruct my program to go back to a specific part of my code and start running from there again.
Another possible way to solve this issue would be to create a way to list out all of the individual files within folder (including all the files within subfolders), and I could easily fit that into my program too.
I tried using labeled continue, return, and break keywords based off of an answer I got online, but I never expected those to succeed in looping my code back to a specific spot.
JFileChooser chooser = new JFileChooser();
chooser.setSelectedFiles(null);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.showOpenDialog(null);
//Getting file paths from within folder
File f = chooser.getSelectedFile();
String file = f.getAbsolutePath();
if (f.isDirectory()) {
//Need to loop back to here
File folder = new File(file);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
//Code here is run if there is a folder within a folder. I tested it too
//I want the code here to loop back above where it says "Need to loop back to here"
}
if (listOfFiles[i].isFile()) { //Once I list the files from within the folder, their information gets assigned variable here, and the rest of my program sorts it and saves it to DB accordingly.
//Everything below here is not important, but it might be helpful to see what happens each file with the folders.
System.out.println(listOfFiles[i]);
String filename = (listOfFiles[i].getName()); //For Files
Long filemodified = (listOfFiles[i].lastModified());
String filepath = (listOfFiles[i].getAbsolutePath());
Long filesizeraw = (listOfFiles[i].length());
long filehashcode = (listOfFiles[i].hashCode());
String fileparent = (listOfFiles[i].getParent());
Currently, there is no error message. It would process any individual files directly in the imported file (not nested in any folder within the folder), but wouldn't get to any of the files that are in folders within folders.
Another possible way to solve this issue would be to create a way to list out all of the individual files within folder (including all the files within subfolders), and I could easily fit that into my program too
Although this doesn't do the SQLite inserts, the following class extracts a list (of File objects) the files (thus file name and path are available via the File object).
public class FTS {
private ArrayList<File> mFileList; //Resultant list of Files extracted
private String mBaseDirectory; // The Directory to search
private long mSubDirectoryCount; // The count of the subdirectories
//Constructor
public FTS(String directory) {
this.mBaseDirectory = directory;
this.mSubDirectoryCount = 0;
buildFileListing(this.mBaseDirectory);
}
//
private void buildFileListing(String directory) {
// Initialise the ArrayList for the result
if (mFileList == null) {
mFileList = new ArrayList(){};
}
//Get the File (directory to process)
File dir = new File(directory);
// Get the List of the Directories contents
String[] filelist = dir.list();
// If empty (null) then return
if (filelist == null) {
return;
}
// Loop through the directory list
for (String s: filelist) {
//get the current list item as a file
File f = new File(dir.getAbsolutePath() + File.separator + s);
// is it a file or directory?
if (f.isFile() && !f.isDirectory()) {
this.mFileList.add(f); // If a file then add the file to the extracted list
} else {
// If a directory then increment the count of the subdirectories processed
mSubDirectoryCount++;
// and then recursively call this method to process the directory
buildFileListing(f.getAbsolutePath());
}
}
}
// return the list of extracted files
public ArrayList<File> getFileList() {
return this.mFileList;
}
// return the number of sub-directories processed
public long getSubDirectoryCount() {
return this.mSubDirectoryCount;
}
}
An example usage of the above is :-
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
FTS fileTreeSearch;
String BaseDirectory = "E:" + File.separator;
List<File> files = (fileTreeSearch = new FTS(BaseDirectory)).getFileList();
System.out.println("Extracted " + String.valueOf(files.size()) + " files, from " + String.valueOf(fileTreeSearch.getSubDirectoryCount()) + " sub-directories of " + BaseDirectory);
/* this commented out code would process all the extracted files
for (File f: files) {
System.out.println("File is " + f.getName() + "\t\t path " + f.getAbsolutePath());
}
*/
}
}
Example output from running the above :-
Extracted 186893 files, from 54006 sub-directories of E:\

Search files by pattern from console by user input - java

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

Scanning sub folder

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
}

Matching a String with a File Name

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;
}
}

Get the folder name of a files parent

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");
}

Categories

Resources