1

I'd like to read the content of the /sys/fs/cgroup/ files (eg. cpuacct.usage) from Java. I've already implemented the reading algorithm based on this answer. The issue is that the cgroup files have 0 length by default. Each of the algorithms listed in the linked answer determines the size of the file before start to read from it, and because the file.length() returns 0, it will attempt to read 0 bytes from the file.

Here is the reading algorithm:

private String readFile(File file) {
    DataInputStream stream = null;
    String content = "";

    try {
        stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
        final byte[] data = new byte[(int) file.length()]; // new byte[1024] throws exception

        stream.readFully(data);
        content = new String(data);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return content;
}

Each file is 0 byte long

Alex
  • 248
  • 2
  • 20

2 Answers2

2

The following approach (using Java NIO) works, even though the OS reports the file length as 0:

String file = "/sys/fs/cgroup/cpu,cpuacct/cpuacct.usage";
String content = new String(Files.readAllBytes(Paths.get(file)));

System.out.println(content); // 972897369764987
Robby Cornelissen
  • 72,308
  • 17
  • 104
  • 121
1

I recommend the IOUtils class in the Apache Commons IO library.

As the content of those files is text, you can use the IOUtils.toString method.

String content = IOUtils.toString(new FileInputStream(file), "UTF-8");
Javi Fernández
  • 836
  • 1
  • 6
  • 14