java - 如何用java编写文件搜索程序?

标签 java linux file jakarta-ee file-io

我想使用适用于Linux和Windows的java进行文件搜索,我可以为Windows制作文件搜索程序,但我对Linux一无所知。我正在使用这个逻辑来显示窗口中的所有磁盘。

package test;

import java.io.File;

public class Test {
public static void main(String[] args) {
    File[] drives = File.listRoots();
    String temp = "";
    for (int i = 0; i < drives.length; i++) {
        temp += drives[i];
    }

    String[] dir = temp.split("\\\\");
    for (int i = 0; i < dir.length; i++) {
        System.out.println(dir[i]);

    }
}
}

以上代码在 Windows 中使用时会显示所有根目录,如 c:,d: 等,在 Linux 中使用时仅显示/。我正在使用这个逻辑在 Windows 中搜索特定文件。

public void findFile(String name,File file)
{
    File[] list = file.listFiles();
    if(list!=null)
    for (File fil : list)
    {
        if (fil.isDirectory())
        {
            findFile(name,fil);
        }
        else if (name.equalsIgnoreCase(fil.getName()))
        {
            System.out.println(fil.getParentFile());
        }
    }
}

它工作正常,但我的问题是如何在 Linux 中制作它,我是 Linux 新手,所以我不知道如何制作它,我的时间不多了,任何帮助都会对我很有帮助。

最佳答案

Java 是独立于平台的,那么您为什么认为必须为 Linux 进行不同的实现呢?

平台依赖项全部由 Java 为您处理。

来自 API (http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listRoots()):

public static File[] listRoots()

List the available filesystem roots.

A particular Java platform may support zero or more hierarchically-organized file systems. Each file system has a root directory from which all other files in that file system can be reached. Windows platforms, for example, have a root directory for each active drive; UNIX platforms have a single root directory, namely "/". The set of available filesystem roots is affected by various system-level operations such as the insertion or ejection of removable media and the disconnecting or unmounting of physical or virtual disk drives.

This method returns an array of File objects that denote the root directories of the available filesystem roots.

并且您不一定必须使用 File.seperator 代替 File.separator vs Slash in Paths 中讨论的反斜杠.

但无论如何这样做可能是个好主意......

关于java - 如何用java编写文件搜索程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22129057/

相关文章:

java - mDrawerList.setOnItemClickListener(new SlideMenuClickListener()) 上的 NullPointerException

java - Gradle , Kotlin : How to add another spring boot project as a module dependency in intellij

python加载静态库

java - 使用 Java 重命名文件

file - 从文件末尾删除换行符

java - Log4j2,如何使用命令行参数控制日志输出目录

java - 如何提高java精度

qt - 使用 Qt 从字符设备读取

linux - 递归计算Linux目录中的文件

c++ - 如何打印 C++ 应用程序中所有线程的列表?