检查输入是文件还是文件夹

时间:2016-12-22 23:36:53

标签: batch-file cmd

我有这样的命令:

set /p txtfile=Write destination to the .txt file:

现在我需要知道文件是否确实存在,所以:

if exist %txtfile% echo file found.

它有效,但是如果用户给我写C:\它将显示"找到文件"至。 我想知道有没有办法知道使用批处理的文件扩展名,任何想法?

3 个答案:

答案 0 :(得分:3)

我假设你想知道给定的项目是现有文件而不是目录(注意目录也可以有扩展名)。使用尾随\来区分文件和目录:

if exist "file.ext" (
    if exist "file.ext\" (
        echo The given item is a directory.
    ) else (
        echo The given item is a file.
    )
) else (
    echo The given item does not exist.
)

或简而言之:

if exist "file.ext" if not exist "file.ext\" echo This is a file but not a directory.

如果您确实要检查给定项目的名称是否有扩展名,可以使用for循环:

for %%I in ("file.ext") do (
    if not "%%~xI"=="" (
        echo The given item has got the extension "%%~xI".
    )
)

答案 1 :(得分:0)

pushd C:\ && (Echo Is a folder & popd) || Echo Is a file or doesn't exist 2>nul

&&if not errorlevel 1相同,||if errorlevel 1相同。 2>nul隐藏错误消息。括号确保通过分组命令按照我的意愿执行行。如果Pushd无法更改为指定的目录errorlevel,则1会将0设置为String json = "{report: [ [ [ BEACH, 59.35 ], [ OCEAN, 40.65 ] ], [ [ OCEAN, 70.2 ], [ BEACH, 29.8 ] ], [ OCEAN, BEACH], [ OCEAN ] ]}"; Gson gson = new GsonBuilder().create(); Map map = gson.fromJson(json, Map.class);

请在此处查看我的命令备忘单Command to run a .bat file

答案 2 :(得分:0)

您可以使用TYPE将其标识为文件。但是,如果它是一个大文件,它可能不是最好的方法。

SET "DIR_ITEM=C:\Windows"

TYPE "%DIR_ITEM%" 1>NUL 2>&1
IF ERRORLEVEL 1 (
    ECHO "%DIR_ITEM%" is not a file
) ELSE (
    ECHO "%DIR_ITEM% is a file
)
相关问题