我正在尝试使用 Java 为 mplayer
开发服务器,但我无法打开名称中包含空格的文件(例如“File with space.mp3”)。
我正在学习本教程 here .问题是,每次我尝试打开名称中有空格的文件时,getInputStream()
只读取空格前的字符串,生成“找不到文件”错误。
命令中的路径是正确的,我什至尝试了不同的格式(例如“File\with\space.mp3”、“$PATH/File with space.mp3”等),但没有任何效果。
如何从 getInputStream
正确获取数据?如何避免 getInputStream
在字符串中发现空格时阻塞?
附言。我用的是linux系统,代码和上面的链接一样(ctrl+c,ctrl+v)。
感谢您的帮助。
最佳答案
问题是 Runtime#exec
的使用。它认为文件中的空间是另一个参数。
Process mplayerProcess = Runtime.getRuntime().exec("/path/to/mplayer -slave -quiet -idle file/to/play.avi");
相反,您应该使用 ProcessBuilder
,它允许您将每个参数指定为单独的 String
,而无需乱用引号。
ProcessBuilder pb = new ProcessBuilder("/path/to/mplayer", "-slave", "-quiet", "-idle", "file/to/play.avi");
// Other configuration options...
Process p = pb.start();
关于java - 如何读取/打开名称中有空格的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16829552/