java 新手,Java与交互式的脚本调用之间传递参数(Java I/O with interactive script)

项目需要,在java里调用一个c++ 二进制可执行文件,而且需要交互式调用,即需要动态地向可执行文件输入参数

具体实行功能:给可执行脚本提供input; 读取脚本执行结果。 google了很多帖子,发现一个好用的。稍稍做了改动。

public void encryLegacy(String password) {
		String[] cmd = { legacyEncryTool, "-e", encryptAlgorith, saltString };
		Process p;
		try {
			p = new ProcessBuilder(cmd).start();
			// read erros
			new Thread(() -> {
				BufferedReader ir = new BufferedReader(new InputStreamReader(p.getErrorStream()));
				String line = null;
				try {
					while ((line = ir.readLine()) != null) {
						LOGGER.error("encrypted passwords '" + password + "' met error:" + line);
					}
					
				} catch (IOException e) {
					LOGGER.error(e.getStackTrace().toString());
				}
			}).start();

			// read data
			new Thread(() -> {
				BufferedReader ir = new BufferedReader(new InputStreamReader(p.getInputStream()));
				String line = null;				
				try {
					while ((line = ir.readLine()) != null) {						
						retString = line;
						writeResult(password + " " + line);//此行式将结果写入文件,不需要的可以注释掉
						LOGGER.debug("password:" + password + " encryped:" + line);
					}
					
				} catch (IOException e) {
					LOGGER.error(e.getStackTrace().toString());
				}
			}).start();

			// read return code
			new Thread(() -> {
				int exitCode = 0;
				try {
					exitCode = p.waitFor();
					System.out.println("++++++pw:" + retString);					
				} catch (InterruptedException e) {
					e.printStackTrace();
					LOGGER.error(e.getStackTrace().toString());
				}
				LOGGER.debug("Encryped passwords return code:" + exitCode);
			}).start();

			// final Scanner sc = new Scanner(System.in);
			/*
			 * final Scanner sc = new Scanner("/root/dd"); final BufferedWriter bf = new
			 * BufferedWriter(new OutputStreamWriter(p.getOutputStream())); final String
			 * newLine = System.getProperty("line.separator"); while(true){ String c =
			 * sc.nextLine(); bf.write(c); bf.newLine(); bf.flush(); }
			 */

			final BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
			bf.write(password);
			bf.newLine();
			bf.flush();
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}		
	}

疑惑的地方: 实例中用了多线程来分别获取inputStream, outputstream,waitforcode. 本来向从这个函数里把执行结果返回给调用函数的地方,可是取不到。发现主线程并没有等子线程退出就退出了。Java新手的我,只能先绕过去了,把结果写到文件里了。

欢迎大家留言解惑。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值