I would like to execute 'top -n 1' command using android and store the output of top command in a file in the internal storage in my device, if possible. Otherwise the file should be stored in sd card. I used the following code to achieve it.
File logFile = new File(getFilesDir().getAbsolutePath()+File.separator+"logtex.txt");
if(!logFile.exists())
{
logFile.createNewFile();
}
logFile.setExecutable(true,false);
logFile.setReadable(true,false);
logFile.setWritable(true,false);
Log.e("executeToplog", "err in");
Runtime.getRuntime().exec("top -n 1 > /data/user/0/com.example.abcdef.memcpuusage/files/logtex.txt ");
But it doesn't seem to work. What changes should be made to the code?
I don't like the idea to fill a file with the output. I would try to following
Process process = Runtime.getRuntime ().exec ("top -1 1");
Reader reader = new InputStreamReader (process.getInputStream ());
// simple approach, omit some checkings, not compiled or tested, so may still fail
FileWriter writer = new FileWriter ("top.log");
for (int chr; (chr = reader.read ()) != –1;) {
writer.append((char) chr);
}
writer.close()
However, it may be that android doesn't support "top", may be you need to apply the full path (on my ubuntu /usr/bin/top)
When you need the output into a file, put the content of reader into that file. ">" is a feature of the shell, not of exec
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.