简体   繁体   English

文件与Java中的随机访问文件

[英]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. 所以我以前将文件存储在File数组中。 My Questions are 我的问题是

1) Does the array contains actual files or the reference to the files? 1)数组是否包含实际文件或对文件的引用? 2) Which is the best option File or RandomAcessFile ? 2)哪个是最好的选择File或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. File是可能存在或可能不存在的文件/目录的抽象表示。 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. RandomAccessFile用于实际的文件访问(读取,查找,写入),因此您在这里不需要它。

1) Java variables like the the one, your array contains, never are the object. 1)像Java变量那样的Java变量,您的数组包含其中一个,永远不是对象。 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. 但是File对象也不是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. 1)file.listFiles该方法返回此抽象路径名表示的目录中文件和目录的路径名数组。

2) Look at this answer https://stackoverflow.com/a/905720/7782618 2)看看这个答案https://stackoverflow.com/a/905720/7782618

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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