简体   繁体   中英

File vs Random Access File in java

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++;
    }
}

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM