「java操作linux」java操作pdf

博主:adminadmin 2022-11-26 00:52:06 69

本篇文章给大家谈谈java操作linux,以及java操作pdf对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java中如何执行linux命令

 执行linux命令基,基本思路是从控制台获得输入的指令,启动命令行执行命令,捕捉异常,示例如下:

public class TestRunTime {

 

    public static void main(String[] args) throws IOException, InterruptedException {

        String cmd = "";

        

        if(args == null || args.length == 0){

            System.out.println("请输入命令行参数");

        }else{

            

            for(int i=0;iargs.length; i++){//获得输入的命令

                cmd += args[i] + " ";

            }

        }

        

 

        try {

            Process process = Runtime.getRuntime().exec(cmd);//执行命令

 

            InputStreamReader ir = new InputStreamReader(process.getInputStream());

            LineNumberReader input = new LineNumberReader(ir);

 

            String line;

            while ((line = input.readLine()) != null) {//输出结果

                System.out.println(line);

            }

        } catch (java.io.IOException e) {

            System.err.println("IOException " + e.getMessage());//捕捉异常

        }

    }

}

怎么用java代码运行linux命令

以下方法支持Linux和windows两个系统的命令行调用。还用到了apache的lang工具包commons-lang3-3.1.jar来判断操作系统类型、也用到了和log4j-1.2.16.jar来打印日志。至于rm -rf 是否能成功删除文件,可以手动去调用命令行试试。

private String callCmd(String cmd) throws InterruptedException, UnHandledOSException, ExecuteException {

        if(SystemUtils.IS_OS_LINUX){

            try {

                // 使用Runtime来执行command,生成Process对象

                Process process = Runtime.getRuntime().exec(

                        new String[] { "/bin/sh", "-c", cmd });

                int exitCode = process.waitFor();

                // 取得命令结果的输出流

                InputStream is = process.getInputStream();

                // 用一个读输出流类去读

                InputStreamReader isr = new InputStreamReader(is);

                // 用缓冲器读行

                BufferedReader br = new BufferedReader(isr);

                String line = null;

                StringBuilder sb = new StringBuilder();

                while ((line = br.readLine()) != null) {

                    System.out.println(line);

                    sb.append(line);

                }

                is.close();

                isr.close();

                br.close();

                return sb.toString();

            } catch (java.lang.NullPointerException e) {

                System.err.println("NullPointerException " + e.getMessage());

                logger.error(cmd);

            } catch (java.io.IOException e) {

                System.err.println("IOException " + e.getMessage());

            }

            throw new ExecuteException(cmd + "执行出错!");

        }

         

        if(SystemUtils.IS_OS_WINDOWS){

            Process process;

            try {

                //process = new ProcessBuilder(cmd).start();

                String[] param_array = cmd.split("[\\s]+");

                ProcessBuilder pb = new ProcessBuilder(param_array);

                process = pb.start();

                /*process=Runtime.getRuntime().exec(cmd);*/

                int exitCode = process.waitFor();

                InputStream is = process.getInputStream();

                InputStreamReader isr = new InputStreamReader(is);

                BufferedReader br = new BufferedReader(isr);

                String line;

                StringBuilder sb = new StringBuilder();

 

                while ((line = br.readLine()) != null) {

                    System.out.println(line);

                    sb.append(line);

                }

                is.close();

                isr.close();

                br.close();

                return sb.toString();

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            throw new ExecuteException(cmd + "执行出错!");

        }

         

        throw new UnHandledOSException("不支持本操作系统");

    }

java程序执行linux命令

首先确保Linux开启sshd服务,并支持远程SSH连接。java程序使用jsch框架登录Linux,执行命令。

protected void creation() throws Exception {

JSch jsch = new JSch();

session = jsch.getSession(userName, host, port);

session.setPassword(password);

Properties config = new Properties();

config.put("StrictHostKeyChecking", "no");

session.setConfig(config);

session.setTimeout(CONNECT_TIMEOUT);

session.setConfig("PreferredAuthentications", "password,keyboard-interactive");

session.setServerAliveInterval(1000 * 60 * 2);

session.connect();

}

public String sendCommand(String command) throws Exception {

if(!isConnected())

throw new JSchException("Session is not connected, command exec faild.");

final ChannelExec exec = (ChannelExec)session.openChannel("exec");

ByteArrayOutputStream out = new ByteArrayOutputStream();

exec.setCommand(command);

exec.setOutputStream(out);

exec.setExtOutputStream(out);

exec.connect();

final Thread thread = new Thread() {

public void run() {

while(!exec.isEOF()) {

try { Thread.sleep(500L); } catch(Exception e) {}

}

}

};

thread.setDaemon(true);

thread.start();

thread.join(EXEC_TIMEOUT);

thread.interrupt();

if(thread.isAlive()) {

throw new JSchException("Exec Time Out Error");

} else {

try {

exec.disconnect();

out.close();

} catch (Exception e) {

}

byte[] lens = out.toByteArray();

String result = new String(lens, charset);

if(result.startsWith("bash") result.indexOf("command not found") != -1)

return "";

return result;

}

}

java操作linux的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java操作pdf、java操作linux的信息别忘了在本站进行查找喔。

The End

发布于:2022-11-26,除非注明,否则均为首码项目网原创文章,转载请注明出处。