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;
}