javafilejarargumentscodepages

Can't open file passing as parameter to jar


If I run my project inside the IDE it works fine: EXISTS c:\testvideos\[video] ролик\video.mp4

but if I run it in the Windows console I'm getting error: NOT exists c:\testvideos\[video] ?????\video.mp

I tried:

Here is the test code:

import java.io.File;
import java.nio.charset.StandardCharsets;

public class TestFileArgument {
    public static void main(String[] args) {
        String fileName = args[0];
//        String fileName = "c:\\testvideos\\[video] ролик\\video.mp4";
        try {
            checkFileExists(fileName);
            checkFileExists(new String(fileName.getBytes("UTF-8"), "windows-1251"));
            checkFileExists(new String(fileName.getBytes("windows-1251"), "UTF-8"));
            checkFileExists(new String(fileName.getBytes("UTF-8"), StandardCharsets.ISO_8859_1.displayName()));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void checkFileExists(String fileName) {
        if (new File(fileName).exists()) {
            System.out.println("EXISTS " + fileName);
        } else {
            System.out.println("NOT exists " + fileName);
        }

    }

}

here is console launch string: c:\Users\Ariloum\.jdks\openjdk-21\bin\java.exe -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8 -jar c:\testvideos\testFileArguments.jar "c:\testvideos\[video] ролик\video.mp4"

if I launch it out of batch file echo shows path correctly without question mark symbols instead of Cyrillic "???????"

Also it fails if filename contains two or more space symbols in a row " ". Is there any workaround for that?


Solution

  • Finally solved this by changing Windows 10 settings, there is one called "Beta: Use Unicode UTF-8 for worldwide language support".

    It's in control panel language settings / administrative lang settings / change system locale.

    With that turned on everything works fine directly with the cmd.exe or Runtime.exec

    Also I've solved another Runtime exec file names issue handling names with double spaces in a row like this:

    String command = "some.exe \"file      n    a m    e   \"";
    Process process = Runtime.getRuntime().exec(command.split(" "));