如何通过Windows批处理文件在名称中创建包含中文字符的文件?

时间:2017-09-09 10:51:14

标签: batch-file unicode character

问题是:

echo HiWorld > c:\filename.txt

filename是中国人。

怎么做?

1 个答案:

答案 0 :(得分:4)

  1. 保存您的批处理文件在UTF-8 ,无 Byte Order Mark
  2. 代码页65001 (即UTF-8 in Windows cmd environment)中运行该批处理文件。
  3. 示例批处理文件

    @ECHO OFF
    SETLOCAL EnableExtensions
    dir /B "D:\bat\UnASCII Names\CJK (中文(繁體))"
    echo HiWorld>"D:\bat\UnASCII Names\CJK (中文(繁體))\中文(繁體).txt"
    dir /B "D:\bat\UnASCII Names\CJK (中文(繁體))"
    type "D:\bat\UnASCII Names\CJK (中文(繁體))\中文(繁體).txt"
    

    输出(您可以看到默认代码页可能是852;您的代码页可能不同):

    ==> chcp
    Active code page: 852
    
    ==> D:\bat\SO\46129875.bat
    File Not Found
    The system cannot find the path specified.
    File Not Found
    The system cannot find the path specified.
    
    ==> chcp 65001
    Active code page: 65001
    
    ==> D:\bat\SO\46129875.bat
    中文(繁體).txt
    HiWorld
    
    ==>
    

    修改:根据有价值的Eryksun's comment

    更新脚本
    @:: How to create a file with Chinese characters in the name by Windows batch file? 
    @:: this file must be saved in `UTF-8` encoding, preferably without Byte Order Mark
    @ECHO OFF
    SETLOCAL EnableExtensions
    :: save the active code page number parsing "Active code page: NNN" output from CHCP
    for /F "tokens=4" %%G in ('chcp') do set "_chcp=%%G"
    :: change the active console code page to UTF-8 
    >NUL chcp 65001
    :: DEBUGGING: erase all .TXT files from target folder 
    >NUL 2>&1 del "D:\bat\UnASCII Names\CJK (中文(繁體))\*.txt"
    :: create a file with Chinese characters in the name inside target folder 
    echo HiWorld>"D:\bat\UnASCII Names\CJK (中文(繁體))\中文(繁體).txt"
    echo Hi All>>"D:\bat\UnASCII Names\CJK (中文(繁體))\中文(繁體).txt"
    :: DEBUGGING: show the name of created file
    dir /B "D:\bat\UnASCII Names\CJK (中文(繁體))"
    :: DEBUGGING: show the content of created file
    type "D:\bat\UnASCII Names\CJK (中文(繁體))\中文(繁體).txt"
    :: change the active console code page back to previously saved value 
    >NUL chcp %_chcp%
    

    <强>输出

    ==> chcp
    Active code page: 852
    
    ==> D:\bat\SO\46129875.bat
    中文(繁體).txt
    HiWorld
    Hi All
    
    ==> chcp
    Active code page: 852
    
    ==>