为媒体创建 URI

creating URI for media

我正在 Java 中创建一个 mp3 播放器。 我想为媒体创建一个 URI。 它仅在文件路径中没有空格时有效,但如果有任何空格,它会抛出 URISyntaxException。

我的 class 中有一个方法可以 return 一个代表我为媒体创建的 URI 的字符串。就是不行。

private static String convertToFileURL ( String filename )
{
    String path = new File ( filename ).getAbsolutePath ();
    if ( File.separatorChar != '/' )
    {
        path = path.replace ( File.separatorChar, '/' );
    }
    if ( !path.startsWith ( "/" ) )
    {
        path = "/" + path;
    }
    URI uri = URI.create(path).normalize();



    String retVal =  "file://" + uri.toString();

    return retVal;
}

有没有更简单的方法来为 RFC 2396 标准创建 URI?

File file = new File(filename);
URI uri = file.toURI();
String retVal = uri.toString();

做你需要的吗?