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));
Related
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.
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();
}
}
File f=new File("C:/");
File fList[] = f.listFiles();
When i use this it list all system file as well as hidden files.
and this cause null pointer exception when i use it to show in jTree like this:
public void getList(DefaultMutableTreeNode node, File f) {
if(f.isDirectory()) {
DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
node.add(child);
File fList[] = f.listFiles();
for(int i = 0; i < fList.length; i++)
getList(child, fList[i]);
}
}
What should i do so that it do not give NullPointerException and show only non hidden and non system files in jTree?
Do this for hidden files:
File root = new File(yourDirectory);
File[] files = root.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return !file.isHidden();
}
});
This will not return hidden files.
As for system files, I believe that is a Windows concept and therefore might not be supported by File interface that tries to be system independent. You can use Command line commands though, if those exist.
Or use what #Reimeus had in his answer.
Possibly like
File root = new File("C:\\");
File[] files = root.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
Path path = Paths.get(file.getAbsolutePath());
DosFileAttributes dfa;
try {
dfa = Files.readAttributes(path, DosFileAttributes.class);
} catch (IOException e) {
// bad practice
return false;
}
return (!dfa.isHidden() && !dfa.isSystem());
}
});
DosFileAttributes was introduced in Java 7.
If running under Windows, Java 7 introduced DosFileAttributes which enables system and hidden files to be filtered. This can be used in conjunction with a FileFilter
Path srcFile = Paths.get("myDirectory");
DosFileAttributes dfa = Files.readAttributes(srcFile, DosFileAttributes.class);
System.out.println("System File? " + dfa.isSystem());
System.out.println("Hidden File? " + dfa.isHidden());
If you are trying to list all files in C:/ please keep in mind that there are other files also which are neither hidden nor system files, but that still won't open because they require special privileges/permissions. So:
String[] files = file.list();
if (files!=null) {
for (String f : files) open(f);
}
So just compare if the array is null or not and design your recursion in such a way that it just skips those files whose array for the list() function is null.
private void nodes(DefaultMutableTreeNode top, File f) throws IOException {
if (f.isDirectory()) {
File[] listFiles = f.listFiles();
if (listFiles != null) {
DefaultMutableTreeNode b1[] = new DefaultMutableTreeNode[listFiles.length];
for (int i = 0; i < b1.length; i++) {
b1[i] = new DefaultMutableTreeNode(listFiles[i].toString());
top.add(b1[i]);
File g = new File(b1[i].toString());
nodes(b1[i], g);
}
}
}
Here is the code I used to create a window file explorer using jtree.
Hi I have a jlist and currently it is viewing a folder + subfolders... Now i would like to change this to view the files in the subfolders as well. below please find the code I am currently using:
jList1.setModel(new javax.swing.AbstractListModel()
{
File folder = new File ("/Assignment_Datex/message_outbox/");
File[] listofFiles = folder.listFiles();
// #Override
public int getSize()
{ return listofFiles.length; }
// #Override
public Object getElementAt(int i)
{ return listofFiles[i];}
}
);
Right now as you can see in the screenshot, the Jlist is only viewing the folders and not the files in them... Any help please?
If you want to show all files and folder under some root folder then you should try someting like this...
Get files and folders under root folder.
Loop over them and check if it is file or folder.
If file then just add to list nothing more.
If folder then add it to list and repeat this same steps for that folder until all folder and files are traveled.
I can not produce whole code here but this is a prototype for this:
void addFilesToList(File folder){
File[] listofFiles = folder.listFiles();
for(File file:listofFile){
if(file.isFile()) // --- file
list.add(file.getName());
else{ // --- folder
addFileToList(file);
}
}
}
The above code is not tested so may need to modify it to fit your need.
#Harry Joy is right.
Additionally you can also use FindFile from jakarta project. It can save your time.
You create a constructor to initialise your class, and there you put (tested and working)
// initialize the class variable
listofFiles = new ArrayList();
// initialize with the path
File f = new File("/home/albertmatyi/Work/python/");
// create a temporary list to work with
LinkedList files = new LinkedList();
// fill it with the contents of your path
files.addAll(Arrays.asList(f.listFiles()));
while (!files.isEmpty()) {
// keep removing elements from the list
f = files.pop();
// if it is a directory add its contents to the files list
if (f.isDirectory()) {
files.addAll(Arrays.asList(f.listFiles()));
// and skip the last if
continue;
}
// check if it's a text file, and add it to listofFiles
if (f.getName().endsWith(".txt"))
listofFiles.add(f);
}
EDIT:
Note:
I've changed the type of listofFiles to ArrayList<File>, which has to be initialized in the constructor using:
listofFiles = new ArrayList<File>();
This allows easier manipulation of the data - no need to manually allocate bigger space for when more text files need to be added
I think this is good way to read all .txt files in a folder and sub folder's
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
String name=(path.get(i)).getName();
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(path.get(i));
}
}
}
}
}
if(input.isFile())
{
String name=(input.getName());
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(input);
}
}
}
}
Now you have a list of files that you can do some process on it!
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