File program in Java

Started by
2 comments, last by Alberth 1 year, 2 months ago

I'd want to create a file search tool in Java that works on both Linux and Windows. I'm familiar with Windows, but I'm not familiar with Linux. This logic is being used to display all of the discs 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]);

    }
}
}

When used in Windows, the above code displays all of the roots such as c:, d:, etc., but when used in Linux, it just displays /. And I'm utilising this reasoning to find a certain 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 works good, but my difficulty is figuring out how to do it in Linux; I'm new to Linux and have no idea how to do it, and I'm running out of time; any assistance would be greatly appreciated.

Advertisement

@fleabay it was today and it went good and i am gonna share the solution here.

Well to use Java to search for a file under Linux, tweak your current findFile method to work with Linux file paths. Because Linux utilises forward slashes (/) to separate file paths, you must replace the backslashes () in your Windows path with forward slashes. Here's a modified version of your approach that should be compatible with both Windows and Linux:

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().getPath().replace('\\', '/'));

}

}

}

}

Furthermore, may cross-platformize your main function by utilising the File.separator system property, which indicates the right file path separator for the current platform:

public static void main(String[] args) {

File[] drives = File.listRoots();

String temp = "";

for (int i = 0; i < drives.length; i++) {

temp += drives[i].getPath() + File.separator;

}

String[] dir = temp.split(File.separator);

for (int i = 0; i < dir.length; i++) {

System.out.println(dir[i]);

}

}

This should give both the Windows and Linux root folders.

You'll find non-existing files if you use a case-sensitive Linux file system,

This topic is closed to new replies.

Advertisement