2014-09-24 86 views
0

我有以下文件夹和文件:如何递归不使用/ S运行DIR命令切换

C:\Test\file.txt 
C:\Test\Folder\file.txt 

我在一个Java程序,查找特定的文件夹,并在其上运行DIR命令工作。该文件夹作为参数传递,并将结果保存在文件中:

cmd /c dir "C:\Test" /s /b /a-D > c:\Test\DIR.txt 

不过,有时候我没有一个文件夹作为参数,我只是有一个文件;我的命令是:

cmd /c dir "C:\Test\file.txt" /s /b /a-D > c:\Test\DIR.txt 

结果是:

C:\Test\file.txt 
    C:\Test\Folder\file.txt 

当参数是一个文件,我只是想将要上市的特定文件(不递归性)。所以,如果我有:

cmd /c dir "C:\Test\file.txt" /s /b /a-D > c:\Test\DIR.txt 

我想要得到的结果是:

C:\Test\file.txt 

我怎样才能做到这一点?如果我有一个文件夹作为参数,消除/ S开关将不正确工作。

任何建议表示赞赏。

+0

如果文件存在,则使用该名称。否则,使用'/ s'参数运行'dir'命令。 – 2014-09-24 21:48:05

回答

0

选项1:添加一个反斜杠结束,测试它是否是一个有效的文件夹:

cmd /c (if exist "somePath\" (dir "somePath" /s /b /a-d) else dir "somePath" /b /a-d) >c:\Test\DIR.txt 

选项2:假设它是一个文件,抑制错误信息,并在第一个命令失败时有条件地执行递归DIR:

cmd /c (dir /b /a-d "somePath" 2>nul || dir /b /a-d /s "somePath") >c:\Test\DIR.txt 
0

能否在Java代码中包含一个检查来查看在调用cmd之前目录/文件夹是否存在?我不知道这样的事Java语法,但在C#我会使用类似:

if (System.IO.Directory.Exists("C:\\Test")) 
{ 
    // start the cmd process with the folder you're after including the /S switch 
} 
else 
{ 
    // The directory won't exist if it's a file, so run it without the /S parameter 
} 

当然,这要看是什么如何你的程序将因为如果你可以实现的那种工作检查与否。但它是一个想法:)

0

IsDirectory.bat

@Echo off 
pushd %1 >nul 2>&1 
If errorlevel 0 if not errorlevel 1 Echo %~nx1 is a folder 
If errorlevel 1 Echo %~nx1 is not a folder 
Popd 

If /i "%cmdcmdline:~0,6%"=="cmd /c" pause 


pause