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:
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:
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:
use StandardCharsets.UTF_16
instead, which has a BOM (but may be either UTF-16 LE or BE):
OutputStreamWriter oStreamWriter = new OutputStreamWriter(..., StandardCharsets.UTF_16);
continue using UTF_16LE
and write a BOM manually before anything else:
OutputStreamWriter oStreamWriter = new OutputStreamWriter(..., StandardCharsets.UTF_16LE);
oStreamWriter.write(0xFEFF);
...