javaoperating-systemlinux-distro

Getting Linux Distro from java


From java, I got name of the OS Iam working. See below code :

System.out.println(System.getProperty("os.name"));

In windows xp, it prints like : Windows XP

But in ubuntu/fedora, it shows only Linux.

Can anyone help me to find which linux version Iam using (like ubuntu or fedora) using java code? Is it possible to find the linux distro from java?


Solution

  • This code can help you:

    String[] cmd = {
    "/bin/sh", "-c", "cat /etc/*-release" };
    
    try {
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader bri = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
    
        String line = "";
        while ((line = bri.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
    
        e.printStackTrace();
    }
    

    UPDATE

    It if you only need the version try with uname -a

    UPDATE

    Some linux distros contain the distro version in the /proc/version file. Here is an example to print them all from java without invoking any SO commands

    //lists all the files ending with -release in the etc folder
    File dir = new File("/etc/");
    File fileList[] = new File[0];
    if(dir.exists()){
        fileList =  dir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String filename) {
                return filename.endsWith("-release");
            }
        });
    }
    //looks for the version file (not all linux distros)
    File fileVersion = new File("/proc/version");
    if(fileVersion.exists()){
        fileList = Arrays.copyOf(fileList,fileList.length+1);
        fileList[fileList.length-1] = fileVersion;
    }       
    //prints all the version-related files
    for (File f : fileList) {
        try {
            BufferedReader myReader = new BufferedReader(new FileReader(f));
            String strLine = null;
            while ((strLine = myReader.readLine()) != null) {
                System.out.println(strLine);
            }
            myReader.close();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }