1 import java.io.BufferedReader;
2 import java.io.BufferedWriter;
3 import java.io.File;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStreamReader;
7 import java.io.OutputStreamWriter;
8
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11
12 /**
13 * 记录当前内存信息
14 *
15 * @author Sx
16 * @version 2013-10-08
17 */
18 public class TopFileUtils {
19 private static final Logger logger = LoggerFactory.getLogger(TopFileUtils.class);
20
21 public static String writeTopMsg() {
22 InputStreamReader isr = null;
23 BufferedReader br = null;
24
25 FileOutputStream fos = null;
26 OutputStreamWriter osw = null;
27 BufferedWriter bw = null;
28
29 String result = "";
30 try {
31 String cmd = "top -b -n 1";// 直接写top输出为空,动态命令,只能加参数输出一次
32 Process ps = Runtime.getRuntime().exec(cmd);
33 isr = new InputStreamReader(ps.getInputStream());
34 br = new BufferedReader(isr);
35 File file = new File("/opt/topmsg.txt");
36 if (!file.exists()) {
37 file.createNewFile();
38 }
39
40 fos = new FileOutputStream(file, true);
41 osw = new OutputStreamWriter(fos);
42 bw = new BufferedWriter(osw);
43
44 StringBuffer sb = new StringBuffer();
45 String line = null;
46 while ((line = br.readLine()) != null) {
47 sb.append(line).append("\n");
48 bw.write(line + "\n");
49 }
50 result = sb.toString();
51 } catch (Exception e) {
52 logger.error("writeTopMsg error:" + e);
53 } finally {
54 try {
55 if (bw != null)
56 bw.close();
57 } catch (IOException e) {
58 logger.error("close bw error:" + e);
59 }
60 try {
61 if (osw != null)
62 osw.close();
63 } catch (IOException e) {
64 logger.error("close osw error:" + e);
65 }
66 try {
67 if (fos != null)
68 fos.close();
69 } catch (IOException e) {
70 logger.error("close fos error:" + e);
71 }
72 try {
73 if (br != null)
74 br.close();
75 } catch (IOException e) {
76 logger.error("close br error:" + e);
77 }
78 try {
79 if (isr != null)
80 isr.close();
81 } catch (IOException e) {
82 logger.error("close isr error:" + e);
83 }
84 }
85 return result;
86 }
87
88 public static void main(String[] args) {
89 System.out.println(writeTopMsg());
90 }
91 }