How to get the file names present in a particular location mentioned - java

Can any one tell me how can I get the file names present in the particular location say
E:/abc_RESPONSE/Response_.
I tried to use The
java.io.File.getName()
method which returns the last name of the pathname's name sequence, that means the name of the file or directory denoted by this abstract path name is returned. But I need all the file names present in that particular location.
String name = (String)(new File("E:/abc_RESPONSE/Response_").getName());
I am using the above code please help to implement this.

Try this..
public void listFiles(String directoryName){
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
System.out.println(file.getName());
}
}
}

try this
String[] names = new File("E:/abc_RESPONSE/Response_").list();

Related

Verify whether the file path contains particular String or not using java

I have one file path which is populated using File interface:-
File folder = new File("C:\\Program Files\\SmartBear\\ReadyAPI-2.2.0\\bin")
File[] listOfFiles = folder.listFiles();
File fOut = listOfFiles[0];
System.out.println(fOut)
It prints all the files inside bin folder. lets say, actions, ext, listeners
Now, I need to verify using if else statement whether the files inside the bin folder contains the particular file I am searching for?
Can we do it using java?
Here is a general example based on String.contains():
String expectedString = "PartOfFilename";
File folder = new File("/path/to/directory");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.getName().contains(expectedString)) {
//matching file found
}
}

Read unknown file names from directory

I would like to read a file from a directory. In this directory there are eight additional files with the same extension (.csv). Likewise, the file name is not directly known.
The name of the file looks like this:
test_file_1_2017_06_24.csv
It can change however, if I call the directory the next day . Then the file name is:
test_file_2_2017_06_25.csv or test_file_1_2017_06_25.
The name of the file and the date change.
Is there a way to read the file "variable" in Java or to read the file but donĀ“t know the exactly name? The directory is always the same ("H:/) (After the file read, then the file respectively the resulting string is furtherprocessed with split() ).
Thanks for helpfull answers!
Edit: Read the directory and shows only csv-Files
File dir = new File("H:/");
File[] fileArray = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".csv");
}
});
for(File f: fileArray){
System.out.println(f.getName());
}
File directory = new File("H:/");
File[] allFilesInDir = directory.listFiles();
See https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles().
You can also provide a FilenameFilter to get only .csv files:
File[] allCsvFiles = directory.listFiles( new FilenameFilter() {
public boolean accept(File dir, String name) {
if ( name.toUpperCase().endsWith(".CSV") ) {
return new File(dir,name).isFile(); // Make sure we don't accept sub-directories ending in .csv
}
}
});
You can use the following code to go through a folder, check for csv files and work with it. Hope it helps.
File folder = new File("H:/"); /*path to your folder*/
String[] filesPresent = folder.list();
if(filesPresent.length==0){
System.out.println("Nothing to delete");
}else{
for(String fileName : filesPresent){ // looping through files in the directory
if(fileName.toLowerCase().endsWith(".csv") && (new File(fileName).isFile())){
//this is a csv file.
//you can do your operations here
File file = new File(fileName);
//now you can do any file operations required with the file object
}
}
}

How to recursively retrieve files from folders returning file name and its Folder name

The code actually retrieves the files but In addition I would also like to get the name of the folder unfortunately, all I keep getting is the path to the folder. I need to extract the sub-directory's/folder's name that contains the files.
public void listAllFilesInTheDirectory(String aDirectoryName){
File directory = new File(aDirectoryName);
File[] allFiles = directory.listFiles();
for (File file : allFiles) {
if (file.isFile()) {
System.out.println("File Name: "+file.getName());
System.out.println("Parent : "+file.getParent());
} else if (file.isDirectory()) {
listAllFilesInTheDirectory(file.getAbsolutePath());
}
}
}
The output:
You may want to use folderFullPath.lastIndexOf(File.separator) in order to find the index of the \ character before the folder name and then use substring to extract the folder name from the full-path.
Are you looking for the parent folder name without the path? If so, use
System.out.println("Parent : "+file.getParentFile().getName());

Case sensitive file extension and existence checking

I need to check whether or not a file exists. Which can be accomplished by File#exists() method. But this existence checking is case sensitive. I mean if I have a file name some_image_file.jpg in code but if physically the file is some_image_file.JPG then this method says that the file doesn't exists. How can I check the file existence with case insensitivity to the extension and get the actual file name?
In my scenario, I have a excel file. Each row contains metadata for files and the filename. In some cases I have only the filename or other cases I can have full path. I am denoting a row as a document.
These files are placed in the server. My job is to
Read the excel file row by row and list all the documents.
Take out the filename or filepath.
Create the full path of the file.
Check if the file exists or not.
Validate other metadata/information provided in the document.
Upload the file.
My application throws exception in case the file doesn't exists or if some metadata are invalid.
The excel file is written by the customer and they wrote some file name wrong, I mean if the file physically have the extension in lower case, they have written the extension in upper case, also the converse is true.
I am running the application in unix server.
As the file extensions are not matching so the File#exists() is giving false and eventually my code is throwing exception.
The folders where the files are placed can have 30000 or more files.
What I want is
To take the full path of the file.
Check if the file exists or not.
If it does not exists then
Check the file existence by converting the case of the extension.
If it doesn't exist after the case conversion then throw exception.
If it exists, then return the actual file name or file path.
If the file name has file extension something like .Jpg, don't know what to do! Should I check it by permuting it by changing the case?
You could get the file names in a folder with
File.list()
and check names by means of
equalsIgnoreCase()
Or try http://commons.apache.org/io/
and use
FileNameUtils.directoryContains(final String canonicalParent, final String canonicalChild)
This way I had solved the problem:
public String getActualFilePath() {
File givenFile = new File(filePath);
File directory = givenFile.getParentFile();
if(directory == null || !directory.isDirectory()) {
return filePath;
}
File[] files = directory.listFiles();
Map<String, String> fileMap = new HashMap<String, String>();
for(File file : files) {
if(file.isDirectory()){
continue;
}
String absolutePath = file.getAbsolutePath();
fileMap.put(absolutePath, StringUtils.upperCase(absolutePath));
}
int noOfOcc = 0;
String actualFilePath = "";
for(Entry<String, String> entry : fileMap.entrySet()) {
if(filePath.toUpperCase().equals(entry.getValue())) {
actualFilePath = entry.getKey();
noOfOcc++;
}
}
if(noOfOcc == 1) {
return actualFilePath;
}
return filePath;
}
Here filePath is the full path to the file.
The canonical name returns the name with case sensitive. If it returns a different string than the name of the file you are looking for, the file exists with a different case.
So, test if the file exists or if its canonical name is different
public static boolean fileExistsCaseInsensitive(String path) {
try {
File file = new File(path);
return file.exists() || !file.getCanonicalFile().getName().equals(file.getName());
} catch (IOException e) {
return false;
}
}

How to get FolderName and FileName from the DirectoryPath

I have DirectoryPath:
data/data/in.com.jotSmart/app_custom/folderName/FileName
which is stored as a String in ArrayList
Like
ArrayList<String> a;
a.add("data/data/in.com.jotSmart/app_custom/page01/Note01.png");
Now from this path I want to get page01 as a separate string and Note01 as a separate string and stored it into two string variables. I tried a lot, but I am not able to get the result. If anyone knows help me to solve this out.
f.getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
For example
File f = new File("/home/jigar/Desktop/1.txt");
System.out.println(f.getParent());// /home/jigar/Desktop
System.out.println(f.getName()); //1.txt
Update: (based on update in question)
if data/data/in.com.jotSmart/app_custom/page01/Note01.png is valid representation of file in your file system then
for(String fileNameStr: filesList){
File file = new File(fileNameStr);
String dir = file.getParent().substring(file.getParent().lastIndexOf(File.separator) + 1);//page01
String fileName = f.getName();
if(fileName.indexOf(".")!=-1){
fileName = fileName.substring(0,fileName.lastIndexOf("."));
}
}
For folder name: file.getParentFile().getName().
For file name: file.getName().
create a file with this path...
then use these two methods to get directory name and file name.
file.getParent(); // dir name from starting till end like data/data....../page01
file.getName(); // file name like note01.png
if you need directory name as page01, you can get a substring of path u got from getparent.
How about using the .split ?
answer = str.split(delimiter);

Categories

Resources