如何在不使用/ S开关的情况下递归运行DIR命令

时间:2014-09-24 21:31:54

标签: cmd

我有以下文件夹和文件:

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开关将无法正常工作。

任何建议都表示赞赏。

3 个答案:

答案 0 :(得分:0)

您是否可以在调用cmd之前检查Java代码以查看目录/文件夹是否存在?我不知道那种东西的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
}

当然,如果您可以实施这种检查,这取决于您的计划将如何运作。但这是一个想法:)

答案 1 :(得分: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

答案 2 :(得分: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
相关问题