Search code examples
javalinuxfilejakarta-eefile-io

How to make file search program in java?


I want to make file search using java that works both for Linux and windows, I am able to make file search program for windows but i am clueless about Linux. I am using this logic to show all the disks in the windows.

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]);

    }
}
}

Above code when used in windows then it will show all the roots like c:,d: etc adn when it is used in Linux it shows only /. And i am using this logic to search specific file in 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());
        }
    }
}

It is working fine but my problem is how to make it in Linux, i am new to Linux so i am clueless how to make it, I am running out of time, any help will be very much helpful for me.


Solution

  • In Linux/Unix system there is only one root directory: /. From the Linux documentation:

    Everything starts from the root directory, represented by /, and then expands into sub-directories instead of having so-called 'drives'.