java调用bat文件传入参数,急,急,急!
使用Runtime.exe()方法,bat文件是需要传入参数的,java的这个方法的参数怎么写,还有bat文件怎么写,举个例子:执行bat要删除某个目录下的某个文件,某个...
使用Runtime.exe()方法,bat文件是需要传入参数的,java的这个方法的参数怎么写,还有bat文件怎么写,举个例子:执行bat要删除某个目录下的某个文件,某个文件是传参的,具体的bat内容怎么写,很急,只有这么多分了
展开
1个回答
展开全部
java好像不能直接给bat文件传参数,不过你可以先生成一个你需要的bat文件,再去执行这个bat文件,我就是这么做的,给你写了个例子,你参考下(你先在d盘下建一个text.txt)
public class DelFile {
public void creatBat(String command){
FileWriter fw=null;
try {
fw=new FileWriter("D:\\del.bat");
fw.write(command);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}finally{
if(fw!=null){
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
}
}
}
private String execute(String batname){
Process process;
String line = null;
StringBuffer sb=new StringBuffer();
try {
process = Runtime.getRuntime().exec(batname);
InputStream fis = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
if(process.waitFor()!=0){
System.out.println("fail");
return "fail";
}
System.out.println(batname+" run successful!");
return "success";
} catch (Exception e) {
e.printStackTrace();
return "fail";
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DelFile df=new DelFile();
df.creatBat("del D:\\text.txt");
df.execute("D:\\del.bat");
}
}
public class DelFile {
public void creatBat(String command){
FileWriter fw=null;
try {
fw=new FileWriter("D:\\del.bat");
fw.write(command);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}finally{
if(fw!=null){
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
}
}
}
private String execute(String batname){
Process process;
String line = null;
StringBuffer sb=new StringBuffer();
try {
process = Runtime.getRuntime().exec(batname);
InputStream fis = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
if(process.waitFor()!=0){
System.out.println("fail");
return "fail";
}
System.out.println(batname+" run successful!");
return "success";
} catch (Exception e) {
e.printStackTrace();
return "fail";
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DelFile df=new DelFile();
df.creatBat("del D:\\text.txt");
df.execute("D:\\del.bat");
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询