简体   繁体   English

如何从任何文件夹运行批处理文件

[英]how to run the batch file from any folder

cd ../../jobs
set CLASSPATH=.;../xyz.jar;../mysql-connector-java-5.1.6-bin.jar
java folser.folder1 ../Files/MySQL.xml
cd ..

I need to run the batch file from any directory. 我需要从任何目录运行批处理文件。 I have set the paths for java. 我已经为java设置了路径。 Can anybody help me? 有谁能够帮助我?

Under *nix (eg Linux): 在* nix下(例如Linux):

cd "`dirname \"$0\"`"
# your current directoy is now the script's directory
cd ../../jobs
set CLASSPATH=.:../xyz.jar:../mysql-connector-java-5.1.6-bin.jar
java folder.folder1 ../Files/MySQL.xml
cd ..
# when the script terminates, you are automatically
#  back to the original directory

Under Windows NT/XP/etc.: 在Windows NT / XP / etc下:

SETLOCAL
PUSHD .
REM current directory has been saved and environment is protected
CD /d %~dp0
REM your current directoy is now the script's directory
CD ..\..\jobs
SET CLASSPATH=.;..\xyz.jar;..\mysql-connector-java-5.1.6-bin.jar
java folder.folder1 ..\Files\MySQL.xml
CD ..
REM before the script terminates, you must explicitly
REM return back to the original directory
POPD
ENDLOCAL

Although I can't comment on Vlad's answer (comments require more points than answers?!) I would always be wary of relying on: 尽管我无法评论弗拉德的答案(评论需要比答案要多的分数?!),我始终会谨慎地依靠:

CD /d %~dp0

because Windows can't CD to UNC paths and has a nasty habit of dropping you into %windir% instead with potentially catastrophic results. 因为Windows无法CD到UNC路径,并且有一个讨厌的习惯,使您陷入%windir%而不是可能带来灾难性的结果。

Instead, although it is more long-winded, you are usually better off referring to %~dp0 (or a variable containing that value) each time you need a full path. 取而代之的是,尽管它耗时较长,但通常每次需要完整路径时,最好引用%〜dp0(或包含该值的变量)。

BAD: 坏:

cd /d %~dp0
rd temp

GOOD: 好:

rd %~dp0\temp

You message was a bit garbled, I'm assuming you're saying that java is on the path but you can't properly run your application from a batch file. 您的消息有点乱码,我假设您是在说java在路径上,但是您无法从批处理文件正确运行应用程序。 It looks like you are missing the classpath option (-cp) for java. 看来您缺少Java的classpath选项(-cp)。 Try this: 尝试这个:

 cd ../../jobs set CLASSPATH=.;../xyz.jar;../mysql-connector-java-5.1.6-bin.jar java -cp %CLASSPATH% folser.folder1 ../Files/MySQL.xml cd .. 

Use %cd% to get the current directory (ie the one that the batch file lives in) 使用%cd%获取当前目录(即批处理文件所在的目录)

eg 例如

 set JAVA_HOME=%cd%\\jdk1.xx set PATH=%JAVA_HOME%\\bin;%PATH% set CLASSPATH=%JAVA_HOME%\\lib\\tools.jar;%cd%\\lib\\myjar.jar;etc,etc 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM