Reputation: 51
I need to search in a directory and get all files in it . so I used to store the file in a File array. My Questions are
1) Does the array contains actual files or the reference to the files? 2) Which is the best option File or RandomAcessFile ? why so ?
please help me with this my code
public File[] getAllFiles(String path) {
File file = new File(path);
if (file.isDirectory() && file.exists()) {
allFiles = file.listFiles();
System.out.println("Files in the directory " + file.getName()
+ " present in the path " + file.getAbsolutePath()
+ " are fetched sucessfully");
printAllFiles(allFiles);
}
return allFiles;
}
public void printAllFiles(File data[]) {
int count = 0;
for (File i : data) {
System.out.println("Index : " + count + " Name : " + i.getName());
count++;
}
}
Upvotes: 2
Views: 2928
Reputation: 197
1) file.listFiles The method returns an array of pathnames for files and directories in the directory denoted by this abstract pathname.
2) Look at this answer https://stackoverflow.com/a/905720/7782618
Upvotes: 1
Reputation: 323
1) Java variables like the the one, your array contains, never are the object. They only point to an object saved somewhere on your disk. So your File Array only point to some File Object on your disk. But File objects are also not the File. They only contain the path to the file and are pointing onto it.
So no, they only point to the files
Upvotes: 2
Reputation: 73528
File
is an abstract representation of a file/directory which may or may not even exist. It doesn't consume any resources, so you can store them as much as you want.
RandomAccessFile
is for actual file access (reading, seeking, writing), so you don't need it here.
Upvotes: 7