javafile-ioinputstreammplayer

How to read/open files with space in name


I'm trying to develop a server for mplayer using Java but I can't open files that have spaces in name (e.g. "File with space.mp3").

I'm following this tutorial here. The problem is, every time I try to open a file with spaces in name the getInputStream() read only the string before the space, generating a "file not found" error.

The path are correct in command, I tried even different formats (e.g. "File\ with\ space.mp3", "$PATH/File with space.mp3", etc), but nothing works.

What can I do to get data properly from getInputStream? How to avoid getInputStream to block when it founds a space in the String?

Ps. I use a linux system and the codes are the same as the link above (ctrl+c , ctrl+v).

thanks for the help.


Solution

  • The problem is the use of Runtime#exec. It thinks that the space in the file is another parameter.

    Process mplayerProcess = Runtime.getRuntime().exec("/path/to/mplayer -slave -quiet -idle file/to/play.avi");
    

    Instead, you should use ProcessBuilder which allows you to specify each parameter as a separate String eliminating the need to mess about with quotes.

    ProcessBuilder pb = new ProcessBuilder("/path/to/mplayer", "-slave", "-quiet", "-idle", "file/to/play.avi");
    // Other configuration options...
    Process p = pb.start();