一直都认为java的jre环境配置比较麻烦,特别是一台pc机器上装了多种不同版本的jre。当一个应用程序在不同的机器上迁移的时候,jre的不同会让你遇到一些意想不到的错误,解决这种问题的方法有两个,一个就是在应用程序中绑上一个jre,让应用程序不管到了哪里,都用的是自己的jre;另一个就是通过改变客户机的jre,比如说向客户机的jre里加入一些应用程序所必需用到的jar包等等。
第一种方法简单是简单,但是有一个最大的弊端,就是附带了jre的应用程序的容量会变得很大,一般情况下至少有增加60MB。。。我原来的程序才1MB多。。。
那就考虑第二种,让客户在运行我的安装程序时,安装程序自动查找到客户机当前使用的jre,并向jre里添加程序所需要的jar包。
以下就是一段取得jre路径的代码,只针对pc平台:
import java.io.*;
public class Setup {
public void createTemp() throws IOException{
Runtime.getRuntime().exec("regedit /ea jrepath.temp \"HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java RunTime Environment\"");
try {
Thread.sleep(1000);//足够的时间间隔
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getJrePath() throws IOException{
File f;
FileReader fr;
BufferedReader br;
f=new File("jrepath.temp");
fr = new FileReader(f);//读取注册表临时文件
br=new BufferedReader(fr);
String line=br.readLine();
while(line!=null){
if(line.indexOf("JavaHome")!=-1){
break;
}
line=br.readLine();
}
br.close();
fr.close();
f.delete();//临时文件删除
String[] info=line.split("\"");
return info[3];
}
public void copyFiles(String filePath1,String filePath2) throws IOException{
File f1,f2;
FileInputStream fin;
FileOutputStream fout;
f1=new File(filePath1);
fin=new FileInputStream(f1);
f2=new File(filePath2);
fout=new FileOutputStream(f2);
int i;
while((i=fin.read())!=-1){
fout.write(i);
}
fout.close();
fin.close();
}
public static void main(String[] artg) throws IOException{
Setup setup=new Setup();
setup.createTemp();
String jrePath=setup.getJrePath();
System.out.println(jrePath);
}
}