am trying to compare all the values in my arraylist with all the files in my c:drive
but the code below does not work
List<String> list = new ArrayList<String>();
list.add("*.txt,*.docx");
File file = new File("c:\\*.txt");
if (file.equals(list)) {
System.out.println("file was found");
}else{System.out.println("nothing was found");
}
so the idea is that anytime i run my the code my arraylist would compare itself with my c: drive and list all files that has the extension of "docx and txt" out.
i realised that when i use wildcards it didn't work.
What you need is a FileNameFilter to get all files that pertain to your requirements
Here is an example of getting all *.txt files from current directory. You can implement FileNameFilter to create your own filter that will work on your List.
File f = new File("."); // current directory
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".txt")) {
return true;
} else {
return false;
}
}
};
File[] files = f.listFiles(textFilter);
Hope this helps.
Related
I want to get the name of the folders from directory who only have .c and .h files.
below is my code but I am not getting that how exactly I can get the folder names who only have .c and .h files.
File directory = new File(directoryName);
//get all the files from a directory
if(directory.exists()){
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isDirectory()){
System.out.println(file.getName());
System.out.println(file.getAbsolutePath());
}
Above code will take the input path for directory and prints the name of all sub folders or sub directories if the main directory is exist.and also prints the path.Now I only want the name of all sub folders from directory which have .c and .h files.
Thanks If anyone help me.
Try to take a look at Apache's DirectoryScanner
Using that we can mention the file extension types to be considered/omitted
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"*.c", "*.h"});
https://ant.apache.org/manual/api/org/apache/tools/ant/DirectoryScanner.html
You can use a list and getParent() function like:
List<String> list;
File directory = new File(directoryName);
if(directory.exists()){
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isDirectory()){
System.out.println(file.getName());
if(file.getName().contains(".c") || file.getName().contains(".h"))
list.add(file.getParent());
System.out.println(file.getAbsolutePath());
}
}
}
for(String item : list) {
System.out.println(item);
}
I've given a pure Java solution here, but if your directory structure is too deep or directories have thousands of files, this may not work out. In that case you may have to run an OS command and dump the output into Java. For instance if you use Unix (or Unix-based) system, you can use find to list directories and invoke the command from Java using ProcessBuilder.
Now the Java solution:
Create a custom FileNameFilter first. This will filter files based on extensions you pass.
public class ExtensionFilter implements FilenameFilter {
private String[] extensions;
public ExtensionFilter(String... extensions) {
this.extensions = extensions;
}
#Override
public boolean accept(File dir, String name) {
for (String extension : extensions) {
if ( name.toLowerCase().endsWith(extension.toLowerCase()) ) {
return true;
}
}
return false;
}
}
Create a FileFilter to help you filter for only directories (for recursion)
public class FolderFilter implements FileFilter {
#Override
public boolean accept(File path) {
return path.isDirectory();
}
}
Use recursion to build list of folder paths contains files with the given extension.
private static final FolderFilter folderFilter = new FolderFilter();
public List<String> recursiveSearch(File base, ExtensionFilter extFilter) {
List<String> paths = new ArrayList<>();
//Does current directory itself have files of given extension?
if (base.list(extFilter).length > 0) {
paths.add(base.getPath()); //Use base.getName() here instead, for just name
}
// Recurse through current directory's subfolders
for (File dir : base.listFiles(folderFilter)) {
paths.addAll(recurse(dir, extFilter));
}
return paths;
}
Finally, invoke it like so:
String basePath = "...";
File baseDir = new File(basePath);
ExtensionFilter extFilter = new ExtensionFilter(".c",".h");
List<String> folders = recurse(baseDir, extFilter);
This will now contain all paths (or names as mentioned above) of folders which have files with given extensions.
I want to list and print them out my src folder. But program is listing all files like .bin .classpat .project. I want to list and print only .ncat extension files. How can i do that ?
File f = null;
String[] paths;
try{
f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");
paths = f.list();
for(String path:paths){
System.out.println(path);
}
}catch(Exception e){
e.printStackTrace();
}
You can define a FileNameFilter :
String[] list = dir.list(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return name.endsWith("suffix");
}
});
Easy way would be to check if the path ends with the extension as follows:
File f = null;
String[] paths;
try{
f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");
paths = f.list();
for(String path:paths){
if(path.toLowerCase().endsWith(".ncat")){
System.out.println(path);
}
}
}catch(Exception e){
e.printStackTrace();
}
Welcome to Stack Overflow.
Take a look at the String.endsWith(String suffix) method (see
here)
and make use of an if-condition.
Update
There is a better solution to this problem. Because this is a homework question (as the questioner mentioned) I will continue to elaborate the obvious way. One may google for FileFilter if he is required to use the "more professional" way.
Moving on: You are iterating over all files that are "stored" inside your paths variable (the for-loop). Inside the loop you are currently printing every file name. What you want to do, is to check if a file ends with the desired extension. If this condition is true, you can print it. If not: don't do anything.
try this
public void filter(){
String[] paths;
try{
f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");
paths = f.list(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return name.endsWith("txt");
}
});
for(String path:paths){
System.out.println(path);
}
}catch(Exception e){
e.printStackTrace();
}
}
I am trying to iterate over a folder
My files a located in
D:\PROJECT_FOLDER\rootProject\semiRootProject\project\build\resources\main\com\xxxx\pack\file.xlsx
However when I try to iterate over it in console it shows
11:39:06.731 [main] INFO com.xxxx.util.KiePackageCreator - File found: D:\PROJECT_FOLDER\rootProject\semiRootProject\project\build\resources\main\com.
What's the problem? My search loop looks like this.
File fileFolder = new File(projectBuildDir + RESOURCE_SUBFOLDER);
for (File file : fileFolder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
//if (name.endsWith(".xlsx")) {
return true;
//}
//return false;
}
})) {
LOGGER.info("File found: {}.", file.toPath());
if (file.isFile()) {
Resource fileResource = getClassPathResource(file.getName());
String filePath = file.getPath();
String rulePath = MAVEN_RESOURCE_PATH + filePath.substring(filePath.indexOf("com"));
LOGGER.info("Attempt to write into: {}.", rulePath);
kfs.write(rulePath, fileResource);
}
}
List files lists all files and directories in the directory you specify. It does not do so recursively.
Maybe walkFileTree suits you better.
You need to iterate through the sub folders in your code. You are just iterating over the files in the directory that fileFolder is pointing to.
Is it possible to read all the names of folders (not sub-folders) inside a directory and save the list in an ArrayList, etc ?
e.g- if a directory has the following folders inside it- CLIENT1, CLIENT2, CLIENT3, etc.
I want the ArrayList to be something like this- [CLIENT1, CLIENT2, CLIENT3, etc].
The folders are in an unix server, so either java code or a shell script(bash/tcsh/etc) or their combination would do.
Try this:
File dir = new File("directoryName");
File temp;
String[] children = dir.list();
if (children !=null) {
for (int i=0; i<children.length; i++) {
temp = new File(children[i]);
if(temp.isDirectory()) //add children[i] to arrayList
}
}
The below Java code snippet should help you. It will return the list of all folders within a directory.It may return an empty list based on the manner in which you deal with any possible IO exception.
public List<String> getDirectoriesInFolder(String folderPath)
{
List<String> folderNames = new ArrayList<String>();
try
{
File directory = new File (folderPath);
String[] allFilesInFolder = directory.list();
for(String fileName : allFilesInFolder)
{
File f = new File(fileName);
if(f.isDirectory)
{
folderNames.add(fileName);
}
}
}
catch(IOException iex)
{
//Do any exception handling here...
}
return folderNames;
}
If you want to do it using Shell scripting then the guidance provided on the below links should help you come to a solution:
help with script to list directories
bash: put output from ls into an array
This would feel slightly cleaner to me than a blunt iteration constructing new File() each time.
public class DirFilter implements FileFilter {
public static FileFilter INSTANCE = new DirFilter();
#Override
public boolean accept(File file) {
return file.isDirectory();
}
}
File startDir = .....;
List<File> children = Arrays.asList(startDir.listFiles(DirFilter.INSTANCE));
I am currently needing to load the contents of a folders filenames to an arraylist I have but I am unsure as how to do this.
To put it into perspective I have a folder with One.txt, Two.txt, Three.txt etc. I want to be able to load this list into an arraylist so that if I was to check the arraylist its contents would be :
arraylist[0] = One
arraylist[1] = Two
arraylist[3] = Three
If anyone could give me any insight into this it would be much appreciated.
Here's a solution that uses java.io.File.list(FilenameFilter). It keeps the .txt suffix; you can strip these easily if you really need to.
File dir = new File(".");
List<String> list = Arrays.asList(dir.list(
new FilenameFilter() {
#Override public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
}
));
System.out.println(list);
File dir = new File("/some/path/name");
List<String> list = new ArrayList<String>();
if (dir.isDirectory()) {
String[] files = dir.list();
Pattern p = Pattern.compile("^(.*?)\\.txt$");
for (String file : files) {
Matcher m = p.matcher(file);
if (m.matches()) {
list.add(m.group(1));
}
}
}
You can try with
File folder = new File("myfolder");
if (folder.isDirectory())
{
// you can get all the names
String[] fileNames = folder.list();
// you can get directly files objects
File[] files = folder.listFiles();
}
Here's My answer, I've used this before personally to get all the filenames,
to be used in a loadsave function in one of my games.
public void getFiles(String path){
//Put filenames in arraylist<string>
File dir = new File(path);
ArrayList<String> filenames = new ArrayList<String>();
for(File file : dir.listFiles()){
savefiles.add(file.getName());
}
//Check if the files are in the arraylist
for (int i = 0; i < savefiles.size(); i++){
String s = savefiles.get(i);
System.out.println("File "+i+" : "+s);
}
System.out.println("\n");
}
I hope that may have been of use to you C: - Hugs rose
See the Jave File API, particularly the list() function.
File my_dir = new File("DirectoryName");
assert(my_dir.exists()); // the directory exists
assert(my_dir.isDirectory()); // and is actually a directory
String[] filenames_in_dir = my_dir.list();
Now filenames_in_dir is an array of all the filenames, which is almost precisely what you want.
If you want to strip the extensions off the individual filenames, that's basic string handling - iterate over the filenames and take care of each one.
Have a look at java.io.File it gives you all the control you may need.
Here is a URL for it http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html