您的位置:首页 > 运维架构 > Shell

java调用windows系统的批处理(.bat文件) 和 linux系统的shell脚本(.sh文件)

2014-01-19 12:31 1011 查看
在批量拷贝系统下的文件时如果用java的IO流来读写文件很消耗系统内存,可能发生内存溢出或宕机,目前的解决方案就是调用系统命令来批量拷贝

java code

public static void copy(String orPath,String newPath)
{
String osName = System.getProperty("os.name");

//linu系统
if(Pattern.matches("Linux.*",osName))
{
//调用shell脚本
Runtime runtime = Runtime.getRuntime();
//copy.sh中 $1==/home/wasadmin/test1/aaa.doc $2==/home/wasadmin/test2
//String[] url = {"/bin/sh","-c","/home/wasadmin/copy.sh /home/wasadmin/test1/aaa.doc /home/wasadmin/test2"};
//由于用空格来区分参数,有的文件名中带有空格,所以用*通配符替换路径中的空格
String[] url = {"/bin/sh","-c","/home/wasadmin/copy.sh "
+(new File(orPath).getPath().replace(" ","*")) +" "+(new File(newPath).getPath())};
try
{
Process process = runtime.exec(url);
process.waitFor();
}catch(Exception e)
{
e.printStackTrace();
System.out.println("copy失败!");
}
}else if(Pattern.matches("Windows.*",osName))
{
//调用批处理文件
try
{
Runtime runtime = Runtime.getRuntime();
//copy.bat中 %1==d:\\test2\\aaa.doc %2==d:\\test3
//Process process = runtime.exec("cmd /c start d/copy.bat d:\\test2\\aaa.doc d:\\test3");
//由于用空格来区分参数,有的文件名中带有空格,所以用*通配符替换路径中的空格
Process process = runtime.exec("cmd /c start d/copy.bat "
+(new File(orPath).getPath().replace(" ","*")) +" "+(new File(newPath).getPath()));
process.waitFor();
}catch(Exception e)
{
e.printStackTrace();
System.out.println("copy失败!");
}
}
}

copy.bat

@echo off
:begin
xcopy /I /E /Y %1 %2
exit

copy.sh
cofile=$1
targetPath=$2
echo "cpFile=${cpFile}" > /home/wasadmin/log
echo "targetPath=${targetPath}" >> /home/wasadmin/log
if(test -e ${cpFile}); then
if(test -d ${targetPath}); then
echo "cp -R ${cpFile} ${targetPath}" >> /home/wasadmin/log
cp -R ${cpFile} ${targetPath}
result=$?
echo "result=${result}" >> /home/wasadmin/log
return $result;
else
echo "the target path is not exist" >> /home/wasadmin/log
return -2;
fi
else
echo "cop file is not exist" >> /home/wasadmin/log
return -1;
fi
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: