【问题标题】:How to read/open files with space in name如何读取/打开名称中有空格的文件
【发布时间】:2013-05-25 15:18:43
【问题描述】:

我正在尝试使用 Java 为 mplayer 开发服务器,但我无法打开名称中包含空格的文件(例如“带空格的文件.mp3”)。

我正在关注本教程here。问题是,每次我尝试打开名称中包含空格的文件时,getInputStream() 只读取空格之前的字符串,从而生成“找不到文件”错误。

命令中的路径是正确的,我尝试了不同的格式(例如“File\ with\ space.mp3”、“$PATH/File with space.mp3”等),但没有任何效果。

如何才能从getInputStream 正确获取数据?如何避免getInputStream在String中找到空格时阻塞?

附言。我用的是linux系统,代码和上面的链接一样(ctrl+c,ctrl+v)。

感谢您的帮助。

【问题讨论】:

标签: java file-io inputstream mplayer


【解决方案1】:

问题在于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();

【讨论】:

  • 非常感谢@MadProgrammer。它就像一个魅力。希望我两天前偶然发现这里。
猜你喜欢
  • 2018-10-23
  • 2020-03-16
  • 2020-09-29
  • 1970-01-01
  • 2021-07-26
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多