I am working on a program that must print the names of each file and subfolder in a given directory.
So far I have the following (this is just the working code):
File directory = new File( [the path] );
File[] contents = directory.listFiles();
for ( File f : contents )
{
String currentFile = f.getAbsolutePath();
System.out.println( currentFile );
}
This needs to be displayed to the user, who doesn't need to see the full path. How can I get the output to only be the file names?
This should help you
File directory = new File("\\your_path");
File[] contents = directory.listFiles();
for (File f : contents) {
System.out.println(f.getName());
}
I suppose that sometimes you might not know the path base (for whatever reason), so there is a way to split the String. You just cut the part before the slash (/) and take all that's left. As you split it, there might be (and probably is) multiple slashes so you just take the last part
String currentFile;
String[] parts;
for ( File f : contents) {
currentFile = f.getAbsolutePath();
parts = currentFile.split("/");
if (!parts.equals(currentFile)) {
currentFile = parts[parts.length-1];
}
System.out.println(currentFile);
}
Example:
"file:///C:/Users/folder/Desktop/a.html" goes to be "a.html"
The file name is being printed as a simple String, meaning that it can be edited. All you have to do is use Str.replace on your path.
This code currentFile = currentFile.replace("[the path]", ""); would replace your file path with a blank, effectively erasing it.
Some code inserted correctly, such as
for ( File f : contents)
{
currentFile = f.getAbsolutePath();
currentFile = currentFile.replace("[the path]", "");
System.out.println(currentFile);
}
will do this for each file your program finds.
Related
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
}
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 can I delete the file in the directory / folder
I am using this code:
private static final String FILE_DIR = "data\\session";
private static final String FILE_TEXT_EXT = ".cache";
private void DeleteCache(String folder, String ext){
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
File fileDelete;
String[] list = dir.list(filter);
for(String file : list){
String temp = new StringBuffer().append(File.separator).append(file).toString();
fileDelete = new File(temp);
boolean isDelete=fileDelete.delete();
System.out.println("File : "+temp+"is Delete : "+isDelete);
}
if(list.length == 0 ) return;
}
public class GenericExtFilter implements FilenameFilter{
private String ext;
public GenericExtFilter(String ext){
this.ext=ext;
}
public boolean accept (File dir, String name){
return (name.endsWith(ext));
}
}
but why yes if, cache do not want to be removed
example error
File : \31052012-TPBSDERG.cache -is Delete : false
Probably because the file does not exist.
Try using....
File[] list = dir.listFiles(filter);
Instead
UPDATE
There are many reasons why a file may not be deleted. The actual process is depended on the underlying OS, but the most common reasons are, the file is open by another process (or your program), you don't have the correct permissions to delete the file and/or the file doesn't exist.
There are a number of interesting issues with your code...
String temp = new StringBuffer().append(File.separator).append(file).toString();
This is appending a file separator to the file which now says, "look for the file in the root directory of the current drive", which is (probably) not where the file exists.
For example;
File dir = new File(System.getProperty("user.home"));
String[] list = dir.list(filter);
for(String file : list){
String temp = new StringBuffer().append(File.separator).append(file).toString();
System.out.println(temp + " - " + new File(temp).exists());
}
This outputs something like...
/.bash_history - false
/.CFUserTextEncoding - false
/.config - false
/.cups - false
Which is obviously wrong, these files don't live in the root folder
Equally if I do;
File dir = new File(System.getProperty("user.home"));
String[] list = dir.list(filter);
for(String file : list){
System.out.println(file + " - " + new File(file).exists());
}
This outputs something like...
.bash_history - false
.CFUserTextEncoding - false
.config - false
.cups - false
This is equally as useless, as these files don't exist in the current execution location either...
Now, however, if I do something like...
String folder = System.getProperty("user.home");
File[] list = new File(folder).listFiles();
for (File file : list) {
System.out.println(file + " - " + file.exists());
}
I get...
/path/to/home/.bash_history - true
/path/to/home/.CFUserTextEncoding - true
/path/to/home/.config - true
/path/to/home/.cups - true
Which is, obviously, far more useful.
You have to remember, Java is stupid, it doesn't know that when you specify a String value for a name where to look for that file, it makes an assumption based on your current location (unless you specify an absolute path of course)
You are iterating over a list of files in folder, but this is NOT where you attempt to delete the files from.
BTW: is that "31052012-TPBSDERG.cache -" the actual file name???
Use this file to delete (and do not prepend with File.separator, the parent folder is what matters):
fileDelete = new File( dir, file );
and it will work. dir.list(filter) only returns file names without path (e.g. directory name), and if dir is not the current working directory, new File( file ) will not point to the file it was included for, new File( dir, file ) will.
I am making an application where the user picks a file from:
FilePicker.PickFile(filename)
where filename is a string.
In the method, it will translate into:
File file = new File(filename);
and nothing is wrong with that. Next, I do,
if(file.exists()){
System.out.println(file.getName());
}
else{
System.out.println("Fail.");
}
and this is where the problem begins. I want to get the name of the file, say "HELLO.txt," but if filename is "hello.txt," it still passes the file.exists() check, and file.getName() returns as "hello.txt," not "HELLO.txt". Is there a way, to return file.getName() as the case-sensitive version as "HELLO.txt?" Thanks!
An example:
HELLO.txt is the real file
FilePicker.PickFile("hello.txt");
OUTPUT:
hello.txt
When you are using Windows, which is case preserving (FAT32/NTFS/..), you can use file.getCanonicalFile().getName() to get the canonical name of the selected file.
When you are using Linux or Android and you want to select a file based on a file name that does not necessarily match case, iterate through all files in the file's directory (file.getParent()), and pick the one that .equalsIgnoreCase the filename. Or see Case-insensitive File.equals on case-sensitive file system
/**
* Maps lower case strings to their case insensitive File
*/
private static final Map<String, File> insensitiveFileHandlerCache = new HashMap<String, File>();
/**
* Case insensitive file handler. Cannot return <code>null</code>
*/
public static File newFile(String path) {
if (path == null)
return new File(path);
path = path.toLowerCase();
// First see if it is cached
if (insensitiveFileHandlerCache.containsKey(path)) {
return insensitiveFileHandlerCache.get(path);
} else {
// If it is not cached, cache it (the path is lower case)
File file = new File(path);
insensitiveFileHandlerCache.put(path, file);
// If the file does not exist, look for the real path
if (!file.exists()) {
// get the directory
String parentPath = file.getParent();
if (parentPath == null) {
// No parent directory? -> Just return the file since we can't find the real path
return file;
}
// Find the real path of the parent directory recursively
File dir = Util.newFile(parentPath);
File[] files = dir.listFiles();
if (files == null) {
// If it is not a directory
insensitiveFileHandlerCache.put(path, file);
return file;
}
// Loop through the directory and put everything you find into the cache
for (File otherFile : files) {
// the path of our file will be updated at this point
insensitiveFileHandlerCache.put(otherFile.getPath().toLowerCase(), otherFile);
}
// if you found what was needed, return it
if (insensitiveFileHandlerCache.containsKey(path)) {
return insensitiveFileHandlerCache.get(path);
}
}
// Did not find it? Return the file with the original path
return file;
}
}
Use
File file = newFile(path);
instead of
File file = new File(path);
It's backed by a cache so it shouldn't be too slow. Did a few test runs and it seems to work. It recursively checks the the parent directories to see if they do have the correct letter cases. Then it lists for each directory all files and caches their correct letter casing. In the end it checks if the file with the path has been found and returns the file with the case sensitive path.
Looks like in Java 7 and above on Windows, you can use Path#toRealPath(NOFOLLOW_LINKS) and it would be more correct than getCanonicalFile() in the presence of symlinks.
Good Day!
I wrote the method in Java which must search files in folders and do some operations with them.
So the problem is that when I try to check what I have (file or dir) I receive nothing in both cases! But as i can see paths look correct.
How can I fix this problem?
Here is the code:
public void searchInDir(){
File inputFile = new File( this.fileName );
String[] namesOfFilesDir = inputFile.list();
for ( int i = 0; i < namesOfFilesDir.length; i++ )
{
String normalPath = this.getNormalPath(inputFile.getCanonicalPath()); //C:\User -> C:\\User
// Two separators for correcting path to file
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
System.out.printf("FileName=%s, Path=[%s]\n", namesOfFilesDir[i], pathToCurrentFile);
System.out.println(f.isDirectory());//False
System.out.println(f.isFile());//False too
//Some other code
}
}
For example this.fileName consists path to folder ( and this folder consists one folder and 2 files).
I got next:
FileName=Readme.txt, Path=[C:\\workspace\\Grep\\t\\Readme.txt]
false
false
FileName=t2, Path=[C:\\workspace\\Grep\\t\\t2]
false
false
FileName=test.txt, Path=[C:\\workspace\\Grep\\t\\test.txt]
false
false
Ok. Program says that.
Lets print next code as an example.
File f = new File("C:\\workspace\\Grep\\t\\Readme.txt");
System.out.println(f.isFile());
Program will print ”True”.
This part makes no sense:
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
Even if we forget about the double separator for the time being, it makes no sense to first construct the file name by adding namesOfFilesDir[i], then construct a File() object using the two-argument constructor which basically adds namesOfFilesDir[i] once more. Try printing f.getAbsolutePath() and you'll see what I mean. It should have probably been something like:
File f = new File( normalPath, namesOfFilesDir[i] );
Probably the file doesn't exist, so it is neither a file nor a directory. Try printing the output of f.exists() as well.
Did you notice the duplicate file separator in your path?
I think that perhaps your paths are not correct. Both isFile() and isDirectory() only return true if the file/directory actually exists. Have you tried calling exists() on the file? Also, I'm suspicious of what your getNormalPath() method is doing - I think it might be mangling the filenames.
The 1st System.out.println is missleading!
It would have been better to output the path of f.
Anyway, according the output:
FileName=Readme.txt, Path=[C:\workspace\Grep\t\Readme.txt]
f will be C:\workspace\Grep\t\Readme.txt\Readme.txt
that is, namesOfFilesDir[i] is being appended twice!
It would be easier/better to work just with instances of File directly:
File inputFile = new File(this.fileName);
File[] files = inputFile.listFiles();
for (File f : files) {
System.out.printf("FileName=%s, Parent=[%s]\n", f.getName(), f.getParent());
System.out.println(f.isDirectory());
System.out.println(f.isFile());
//Some other code
}