ShellUtil.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package com.fdkankan.fusion.common.util;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.io.BufferedReader;
  4. import java.io.Closeable;
  5. import java.io.InputStreamReader;
  6. @Slf4j
  7. public class ShellUtil {
  8. /**
  9. * 执行系统命令, 返回执行结果
  10. * @param cmd 需要执行的命令
  11. */
  12. public static void execCmd(String cmd) {
  13. StringBuilder result = new StringBuilder();
  14. Process process = null;
  15. BufferedReader bufrIn = null;
  16. BufferedReader bufrError = null;
  17. long startTime = System.currentTimeMillis();
  18. try {
  19. // 执行命令, 返回一个子进程对象(命令在子进程中执行)
  20. log.info("执行cmd:{}",cmd);
  21. process = Runtime.getRuntime().exec(cmd);
  22. // 方法阻塞, 等待命令执行完成(成功会返回0)
  23. process.waitFor();
  24. // 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出(PS: 子进程的输出就是主进程的输入)
  25. bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
  26. bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
  27. // 读取输出
  28. // String line = null;
  29. // while ((line = bufrIn.readLine()) != null) {
  30. // result.append(line).append('\n');
  31. // }
  32. // while ((line = bufrError.readLine()) != null) {
  33. // result.append(line).append('\n');
  34. // }
  35. }catch (Exception e){
  36. e.printStackTrace();
  37. }finally {
  38. closeStream(bufrIn);
  39. closeStream(bufrError);
  40. // 销毁子进程
  41. if (process != null) {
  42. process.destroy();
  43. }
  44. }
  45. // 返回执行结果
  46. log.info("执行cmd:{},结果:{},耗时:{}", cmd,result.toString(),System.currentTimeMillis() -startTime);
  47. }
  48. private static void closeStream(Closeable stream) {
  49. if (stream != null) {
  50. try {
  51. stream.close();
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. }
  57. public static void unZip(String zipPath, String dataPath) {
  58. log.info("解压zip开始");
  59. String command = "unzip -O GBK/GB18030CP936 " + zipPath + " -d " + dataPath;
  60. execCmd(command);
  61. log.info("解压zip完毕:" + command);
  62. }
  63. public static void unRar(String rarPath, String dataPath) {
  64. log.info("解压rar开始");
  65. String command = "unrar e " + rarPath + " " + dataPath;
  66. execCmd(command);
  67. log.info("解压rar完毕:" + command);
  68. }
  69. }