簡體   English   中英

執行linux命令並將輸出存儲在android文件中

[英]Execute linux command and store output in a file android

我想使用android執行'top -n 1'命令,並在可能的情況下將top命令的輸出存儲在設備內部存儲器中的文件中。 否則,文件應存儲在SD卡中。 我使用以下代碼來實現它。

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 ");

但這似乎不起作用。 應該對代碼進行哪些更改?

我不喜歡用輸出填充文件的想法。 我會嘗試跟隨

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()

但是,可能是android不支持“ top”,可能是您需要應用完整路徑(在我的ubuntu / usr / bin / top上)

當需要將輸出輸出到文件中時,將閱讀器的內容放入該文件中。 “>”是shell的功能,而不是exec的功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM