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

Cmd 如何在不使用/S开关的情况下递归运行DIR命令,cmd,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:

我有以下文件夹和文件:

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


非常感谢您的建议。

在调用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
}
当然,这取决于你的程序将如何工作,如果你能实现这种检查与否。但这是一个想法:)

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

选项1:在末尾添加反斜杠,并测试其是否为有效文件夹:

cmd /c (if exist "somePath\" (dir "somePath" /s /b /a-d) else dir "somePath" /b /a-d) >c:\Test\DIR.txt
选项2:假设它是一个文件,抑制错误消息,并在第一个命令失败时有条件地执行recursive DIR:

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

如果文件存在,则使用该名称。否则,使用
/s
参数运行
dir
命令。