2014-09-24 23 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