Java 启动外部程序注意事项

来源:互联网 发布:优化9事件修改 编辑:程序博客网 时间:2024/04/28 01:51
   Runtime.getRuntime().exec();方法 启动 新的进程,实现调用外部程序的功能。对于普通的.exe文件或其他可执行文件,可以直接将"路径+ *.exe",传给exec()的形参,而对于使用命令方式启动,并没有直接的可执行文件的情况:
    推荐使用.bat文件封装此命令,成为一个.bat的可执行文件,然后思路同上!

     下面的程序段,其中注意几个问题:

     1  exec()方法参数有几种,参见帮助文档。如果使用字符串数组传值,则exec()自动将数组第一个元素视为可执行文件,以后的元素视为命令参数。

   public Process exec(String[] cmdarray)
   cmdarray[0]指的是命令(可执行文件),
   cmdarray[1],
   cmdarray[2],
   cmdarray[3],等指的是参数,而

   public Process exec(String cmd)
   的cmd是命令+参数
   执行时jvm会把它拆开来,成为cmdarray[0] + cmdarray[1]……
2  exec("cmd.exe /c copy );采用先启动命令行,再使用使用命令行的参数 /c加上执行命令,copy 的方式也可以启动copy命令。

3  无论对于封装在 .bat 文件中的,还是写在exex() 函数中的,文件路径问题,经常遇到如下两个羁绊:

   1)路径中 的 使用双反斜杠,//

   2)路径中文件夹的名字涉及到空格的 ,比如C:/Documents and Settings

   因该格外注意,看是不是使用转义符号解决,,
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;

public class Optimize {
 public static void main(String srg[]) {

  String[] cmd = {"l://ww.bat"};
  Runtime rt = Runtime.getRuntime();
  try {
   Process pro = rt.exec(cmd[0]);

   InputStream in = pro.getInputStream();
   byte[] s= new byte[1024];
   StringBuffer sb = new StringBuffer();
   int size = 0;
   while ((size = in.read(s)) >= 0) {
    sb.append(new String(s, 0, size));
   }  
  }
  catch (IOException e) {
   e.printStackTrace();
  }

  //以下是读取文件的代码段
  RandomAccessFile rf = null;

  String name = "fencetest";
  String fileLuJing = "L://" + name + ".db";
  ArrayList<String> ziFu = new ArrayList<String>();//每一行的字符串为一个元素

  try {
   rf = new RandomAccessFile(fileLuJing, "r");
   long len = rf.length();
   long start = rf.getFilePointer();
   //System.out.println(start);
   long nextend = start + len - 1;
   String eachLine;//用于向ArrayList添加元素的代表
   String lastLine;//最后一行的字符串
   String firstLine = rf.readLine();
   rf.seek(start);
   int c = -1;
   while (start<nextend) {
    c = rf.read();
    if (c == '/n' || c == '/r') {
     eachLine= rf.readLine();
     ziFu.add(eachLine);

    }
    rf.seek(start);
    start++;   

   }
   rf.close();
   lastLine = ziFu.get(ziFu.size()-1); 
   System.out.println(lastLine);
   System.out.println(firstLine);
  }
  catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  catch (IOException e) {
   e.printStackTrace();
  }
  finally {
   try {
    if (rf != null)
     rf.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }


 }
}

 
原创粉丝点击