Pyl2457148085 2019-05-13 16:07 采纳率: 91.7%
浏览 2257
已采纳

java执行Linux的cd指令

如何用java代码模拟linux系统下的命令

例如 我要进入某个目录 在linux下我直接敲字符 cd /bin/usr/test

在java中如何用代码来实现这个操作,拜托大佬们给小弟解解惑!

  • 写回答

2条回答 默认 最新

  • 毕小宝 博客专家认证 2019-05-14 09:15
    关注

    Java 提供了调用 Linux 命令的方法:

    public static List<String> executeComm(String comm){
    
            List<String> strList = new ArrayList<String>(); 
            Process process = null;
            BufferedReader in = null;
            try {
                //整个命令作为sh的参数进行执行,以便执行重定向和管道命令,否则管道命令会被当成参数执行,得到错误结果
                String[] arr = new String[]{"/bin/sh", "-c", comm};
                process = Runtime.getRuntime().exec(arr); // 执行添加权限的命令
                process.waitFor(); // 如果执行多个命令,必须加上
    
                in = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String str = null;
                while ((str = in.readLine()) != null) {
                    strList.add(str);
                }
            } catch (IOException e) {
                logger.error("执行 Shell 时,出现IO异常,设置失败",e);
            } catch (InterruptedException e) {
                logger.error("设置 IP 时,出现InterruptedException异常,设置失败",e);
            }finally {
                if(in != null){
                    try {
                        in.close();
                    } catch (IOException e) {
                        logger.error("关闭输入流失败",e);
                    }
                }
                if(process != null){
                    process.destroy();
                }
            }
            return strList;
        }
    

    自己写个main 方法,把 日志打印的换成 System.out 。调用参数为 cd /dir

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制