Adb pull file with special character in its path

2019-07-16 09:21发布

问题:

I am trying to copy a file from my phone to my pc using adb over network. My code works perfectly fine even for files with spaces in their path, but it fails for files containing any special character for example "ß á ö" and thats my problem.

I need to execute this command from java and I am currently using this code to pull the file:

public static void pullFile() {
    try {
        // Setting file paths
        String androidFilePath = "\"/storage/sdcard0/Download/Bußgeld 2014 TGC.pdf\"";
        String windowsFilePath = "\"C:\\Dropbox\\Java Projekte\\ADB Browser\\bin\\files\\Bußgeld 2014 TGC.pdf\"";
        System.out.println(androidFilePath);
        System.out.println(windowsFilePath);

        // Building command
        List<String> cmd = new LinkedList<>();
        cmd.add("adb");
        cmd.add("pull");
        cmd.add(androidFilePath);
        cmd.add(windowsFilePath);

        // Running command
        ProcessBuilder builder = new ProcessBuilder(cmd);
        builder.redirectErrorStream(true);
        Process p = builder.start();

        // Getting the output from the command ...

        System.out.println(stringBuilder.toString);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

When I run this code I am getting the following error: remote object '/storage/sdcard0/Download/Bu�geld 2014 TGC.pdf' does not exist

My question now is how do I correctly escape the characters for the adb.

I´ve tried to use

ByteBuffer buf = Charset.forName("UTF-8").encode(androidFilePath);
androidFilePath = new String(buf.array(), "UTF-8");

but this way I get some trailing whitespaces, which i can´t remove since trim will return a new String, which isn´t encoded with "UTF-8";

Ok i figured out, that it probably isn´t the fault of the java code! I ran the command from cmd as well as windows powershell and both returned:

remote object '/storage/sdcard0/Download/Bu▀geld 2014 TGC.pdf' does not exist

回答1:

I managed to solve the problem (which is apparently a bug in adb Issue 8185: adb push doesn't accept unicode filenames ) by using the following code snippet to encode the path.

byte ptext[] = androidFilePath.getBytes("UTF-8");
androidFilePath = new String(ptext, "CP1252");