javautf-8character-encoding

UTF-16LE encoded Desktop.ini generated by java does not works when it contains chinese characters


I am trying to create a desktop.ini file through java to provide an alternative name for Windows11 folder (Just as My Documents looks like).

Here is a simple code example(It can be called directly to run):

@Test
public void createDesktopIni() throws IOException {
    String folderPath = Write a folder path here;
    String iniPath = folderPath + "\\desktop.ini";
    File file = new File(iniPath);
    // delete and recreate if exist
    if (file.exists()) {
        file.delete();
    }
    file.createNewFile();
    // Write content
    String alternativeName = "Alternative Name";
    //alternativeName = "这是一个中文别名";
    OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_16LE);
    oStreamWriter.write("[.ShellClassInfo]\nLocalizedResourceName = " + alternativeName);
    oStreamWriter.flush();
    oStreamWriter.close();
    // Set system attribute
    Files.setAttribute(Paths.get(folderPath), "dos:system", true, LinkOption.NOFOLLOW_LINKS);
    Files.setAttribute(Paths.get(iniPath), "dos:system", true, LinkOption.NOFOLLOW_LINKS);
    Files.setAttribute(Paths.get(iniPath), "dos:hidden", true, LinkOption.NOFOLLOW_LINKS);
}

If I set an English alternative name, the desktop.ini can work normally. (By the way, this file can be opened normally through VSCode at this time).

However, if i set a chinese alternative name such as comment:

alternativeName = "这是一个中文别名";

At this time, the desktop.ini file cannot works.

If I open it through VSCode, the following content will be displayed: VS Code Error Message

But if I choose Open Anyway->Reopen with UTF-16 LE Encoding, and then save the file as UTF-16 LE through VS Code, it works fine again.

Here are some other encodings I tried:

  1. UTF-8 works, but Chinese characters are garbled in Explorer.exe.
  2. GBK works, and it is not garbled. But I prefer to use UTF-16, I see that the desktop.ini in My Documents folder also uses UTF-16 LE.
  3. UTF-16 not works, and the file will be encoded to UTF-16 BE.

Solution

  • A Desktop.ini file (or really, any INI file on Windows) that contains Unicode characters must begin with a UTF-16 BOM so the Win32 API knows the content is Unicode. but you are not producing a BOM as you are using StandardCharsets.UTF_16LE which is BOM-less.

    You can either: