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

在批量拷贝系统下的文件时如果用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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值