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!
Related
Ok so part of my program searches the C drive for all mp3 files, the only problem is that it won't go into and subfolders. Here is my code so far.
public static List<String> ListFiles() {
List<String> files = new ArrayList<String>();
File folder = new File("C:/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile() && file.toString().contains(".mp3")) {
String fileS = file.getName();
files.add(fileS);
}
}
return files;
}
Try a recursive approach. The path is the current directory that you're in. Recursively call this on each folder and you will get to each file.
public void walk(String path) {
File root = new File(path);
File[] list = root.listFiles();
if (list == null) return;
for (File f : list) {
if (f.isDirectory()) {
walk(f.getAbsolutePath());
}
else {
//do what you want with files
}
}
}
Test whether file is a folder. If it is, pass it to ListFiles and append the return value to files.
For this to work, you need to change ListFiles to accept a File object as argument and start your search with this File instead of with "C:/"
Look into DirectoryStream<Path> class and the Files.isDirectory() method. Basically what you want to do is to check whether each Path is a file or directory.
If it is a directory, you call your method again. Else, you continue iterating.
Globbing is also possible with a directory stream. Saves you a lot of time instead of having to manually check file extensions.
If you wish to continue with your method or with directory stream, you will need to make a few modifications to your program to accomodate recursion.
If you want to do this yourself, you need to make it recursive. Which is what Oswald is getting at. A recursive method is a method that calls itself. So when you search a folder, for each element in it, if its an mp3, add it to the list, if its a folder, call your method again passing that folder in as the input.
I know it's Java question but why not just use Groovy and do it like:
static List<String> listMp3s() {
List<String> files = []
File rootFolder = new File('C:/')
rootFolder.eachFileRecurse(FileType.FILES) {
if (it.name.endsWith('.mp3')) {
files << it.name
}
}
return files
}
I'm trying to write this script that takes an Excel sheet, gets all the names of files from the cells, and moves each of those files to a specific folder. I've already got most of the code done, I just need to be able to search for each file in the source directory using just its title. Another problem is that I'm searching for multiple file types (.txt, .repos, .xlsx, .xls, .pdf, and some files don't have extensions), I only can search by the file name without the extension.
In my findAndMoveFiles method, I've got an ArrayList of each File and a Guava Multimap of XSSFCells to Strings (a cell is one cell from the Excel file and a String is the name of the folder it needs to go into, one to many relationship) as parameters. What I've got right now for the method is this.
public static void findAndMoveFiles(List<File> files, Multimap<XSSFCell, String> innerCells) {
// For each file, get its values (folders), and put that file in each of those folders
for (XSSFCell cell : innerCells.keySet()) {
// find the file in the master directory
//Finder f = new Finder();
//if (f.canBeFound(FOLDER, cell.getStringCellValue())) {
File file = find(FOLDER, cell.getStringCellValue());
//System.out.println(file.getAbsolutePath());
//List<String> values = new ArrayList(innerCells.get(cell));
/*for (String folder : values) {
File copy = file;
if (copy != null) {
System.out.println(folder);
System.out.println(copy.getAbsolutePath());
if (copy.renameTo(new File("C:\\strobell\\" + folder + "\\" + copy.getAbsolutePath()))) {
System.out.println(copy.getName() + " has been moved successfully.");
} else {
System.out.println(copy.getName() + " has failed to move.");
}
}
}*/
//}
}
}
public static File find(File dir, String fileName) {
String files = "";
File[] listOfFiles = dir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getAbsolutePath();
if (files.equals(fileName)) {
return listOfFiles[i];
}
}
}
return null;
}
I commented out parts because it wasn't working. I was getting NullPointerExceptions because some files were being returned as null. I know that it's returning null, but each file should be found.
If there are any 3rd party libraries that can do this, that would be amazing, I've been racking my brain on how to do this properly.
Instead of
File[] listOfFiles = dir.listFiles();
use
File[] listOfFiles = dir.list(new FileNameFilter() {
public boolean accept(File dir, String name) {
if( /* code to check if file name is ok */ ) {
return true;
}
return false;
}
}););
Then you can code your logic on the file names in the condition.
Can someone help me with reading a list of list of csv files. Like
List<List<File>> filesList;
Want to read through all the files contents in each list for processing, but unable to comeup with loop structure which can be used. Thanks.
UPDATE: I want to load files from each inner file list simultaneously. Like read first file from each inner list at a time, compare contents, then move to second file of a particular list and so on. Each inner list can be of variable size.
Here's an appropriate loop for this:
for (List<File> innerList : filesList)
for (File file : innerList)
// do something for a file
Alternatively you can use Iterator,like this
List<ArrayList<File>> filesList = new ArrayList<ArrayList<File>>();
//add objects to filesList here
Iterator<ArrayList<File>> filesListIterator = filesList.iterator();
while(filesListIterator.hasNext())
{
ArrayList<File> files = filesListIterator.next();
Iterator<File> filesIterator = files.iterator();
while(filesIterator.hasNext())
{
File file = filesIterator.next();
//do your own logic here;
}
}
Update
This may help you for compare
while(filesListIterator.hasNext())
{
ArrayList<File> files = filesListIterator.next();
for(int i=0;i<files.size()-1;i++)
{
File firstFile = files.get(i);//get a file
File secondFile = files.get(i+1);//get the next file
compareFiles(firstFile,secondFile);//this is your defined
//method for compare
}
}
List<List<File>> filesList;
for (List<File> list : filesList) {
for (File file : list) {
// your code here ...
}
}
Personally I would recommend using Google Guava if you can, this has a concat method
final List<List<File>> files = Lists.newArrayList();
for (final File file : Iterables.concat(files)) {
//doStuff with file
}
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 trying to get a report file which is generated for many applications and stored in directories. But i am not able to get every report when i search through java. Can any 1 please help me with this matter.
if you want to search the file in a directory that has subdirectory and goes on then use a recursive search.you can see an example here http://www.exampledepot.com/egs/java.io/TraverseTree.html
http://www.java2s.com/Code/Java/File-Input-Output/Searchforfilesrecursively.htm
private static File find(File dir, String name) {
File result = null; // no need to store result as String, you're returning File anyway
File[] dirlist = dir.listFiles();
for(int i = 0; i < dirlist.length; i++) {
if(dirlist[i].isDirectory()) {
result = find(dirlist[i], name);
filedetails.add(result);
if (dirlist==null)
break;
// recursive call found the file; terminate the loop
} else if(dirlist[i].getName().matches(name)) {
return dirlist[i]; // found the file; return it
}
}
return result; // will return null if we didn't find anything
}
here is snippet where i am trying details of the file in a vector .
File Dir = new File("D:\\log");
File[] Dir2 = Dir.listFiles(); //Dir2 is inner directory
for(int j=0;j
/* The add gets the same file names which as differnt path and that vector can stored and used */