Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File vs Random Access File in java

Tags:

java

io

nio

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++;
    }
}
like image 845
somes k Avatar asked Feb 24 '26 08:02

somes k


2 Answers

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.

like image 145
Kayaman Avatar answered Feb 25 '26 20:02

Kayaman


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

like image 36
Donatic Avatar answered Feb 25 '26 20:02

Donatic