0

I want to get the version of Linux using Java code. In different Linux distributions I have file with diffrent name.

/etc/*-release

How I can get every file content which ends with -release?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • The latest version != current version. Do you like to know the current running linux version? – Grim Apr 28 '14 at 11:52

5 Answers5

6

You can use File.listFiles(FilenameFilter)

    File f = new File("/etc/");
    File[] allReleaseFiles = f.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith("-release");
        }
    });
sanbhat
  • 17,522
  • 6
  • 48
  • 64
  • Is this the best solution? Can I optimize this code? – Peter Penzov Apr 28 '14 at 11:33
  • What do you want to optimize here? The code is short, precise and readable. You apply a filter to a list of files, the resulting ``File[]`` contains exactly the files you ask for. – f1sh Apr 28 '14 at 11:35
  • @PeterPenzov Did you try it out? Was it too slow? Don't optimize too soon – Absurd-Mind Apr 28 '14 at 11:35
  • @PeterPenzov This is just a convenience given by API. If you want to do it yourself, you can list all files within `etc` folder and add only those which ends with `release`, in a `for loop`. I don't think you can further optimize this. – sanbhat Apr 28 '14 at 11:36
2

Use Java java.io.File#listFiles and then simply iterate over the array that it returns to open the files.

Loic Duros
  • 5,472
  • 10
  • 43
  • 56
1
System.getProperty("os.version")
Grim
  • 1,938
  • 10
  • 56
  • 123
0

You can get files by getting output after executing ls -d /etc/*-release.

And then work with them via Java File.

See also:

Community
  • 1
  • 1
Rong Nguyen
  • 4,143
  • 5
  • 27
  • 53
0

Surely, you should use nio nowadays for this type of action:

Path dir = Paths.get("/etc");
for (Path file : Files.newDirectoryStream(dir, "*-release"))
    System.out.println (new String(Files.readAllBytes(file), "UTF-8"));
Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48