如何启动一个命令,如何读取程序的一些内容和写一些东西到该进程中?

关于子进程对象有三个重要的方法。p.getErrorStream(),p.getOutputStream(),p.getInputStream();

package com.huxin.testfifteen.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/*
 * 本程序可以解决如何启动一个进程,如何读取一个进程的相关信息。
 */
public class ReadFromProcess {
 public static void main(String[] args) {
  InputStreamReader is = null;
  BufferedReader bf = null;
     try {
   Process p = Runtime.getRuntime().exec("javac");  //运行javac的命令,并且返回一个子进程的对象。
      is = new InputStreamReader(p.getErrorStream());  //返回的是一个字节流
      bf = new BufferedReader(is);
   String str = null;
   while((str = bf.readLine())!=null){
    System.out.println(str);
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally{
   try {
    bf.close();
    is.close();
   } catch (IOException e) {
    e.printStackTrace();
   }  
  }

 }
}

 

package com.huxin.testfifteen.io;

import java.io.IOException;
import java.io.PrintStream;

/*
 * 本程序解决如何启动一个程序,和如何向一个进程写东西。
 */
public class WriteFromProcess {

 public static void main(String[] args) {
     try {
   Process p = Runtime.getRuntime().exec("java ReadStadard");
   PrintStream ps = new PrintStream(p.getOutputStream());
   ps.print("我自己写了一点东西,看看能不能写到那个进程中去");  
  } catch (IOException e) {
   e.printStackTrace();
  }

 }
}

 

package com.huxin.testfifteen.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;

public class ReadStadard {
 public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    sc.useDelimiter("\n");                        //以回车作为分隔符
    PrintStream ps = null;
    try {
   ps = new PrintStream(new FileOutputStream("D:\\test3.txt"));
   while(sc.hasNext()){
    ps.print(sc.next());    //如果要写一个字符的话,就用PrintStream的处理流
   }
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    }finally{
     ps.close();   
    }
 }
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值