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
}
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
}
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));
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 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 */
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