Java: Get URI from FilePath

前端 未结 5 861
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 17:11

I\'ve little knowledge of Java. I need to construct a string representation of an URI from FilePath(String) on windows. Sometimes the inputFilePath

相关标签:
5条回答
  • 2020-12-03 17:38

    The argument to new File(String) is a path, not a URI. The part of your post after 'but' is therefore an invalid use of the API.

    0 讨论(0)
  • 2020-12-03 17:45

    These are the valid file uri:

    file:/C:/a.txt            <- On Windows
    file:///C:/a.txt          <- On Windows
    file:///home/user/a.txt   <- On Linux
    

    So you will need to remove file:/ or file:/// for Windows and file:// for Linux.

    0 讨论(0)
  • 2020-12-03 17:46
    class TestPath {
    
        public static void main(String[] args) {
            String brokenPath = "file:/C:/a.txt";
    
            System.out.println(brokenPath);
    
            if (brokenPath.startsWith("file:/")) {
                brokenPath = brokenPath.substring(6,brokenPath.length());
            }
            System.out.println(brokenPath);
        }
    }
    

    Gives output:

    file:/C:/a.txt
    C:/a.txt
    Press any key to continue . . .
    
    0 讨论(0)
  • 2020-12-03 17:47

    Just use Normalize();

    Example:

    path = Paths.get("/", input).normalize();
    

    this one line will normalize all your paths.

    0 讨论(0)
  • 2020-12-03 17:48

    From SAXLocalNameCount.java from https://jaxp.java.net:

    /**
     * Convert from a filename to a file URL.
     */
    private static String convertToFileURL ( String filename )
    {
        // On JDK 1.2 and later, simplify this to:
        // "path = file.toURL().toString()".
        String path = new File ( filename ).getAbsolutePath ();
        if ( File.separatorChar != '/' )
        {
            path = path.replace ( File.separatorChar, '/' );
        }
        if ( !path.startsWith ( "/" ) )
        {
            path = "/" + path;
        }
        String retVal =  "file:" + path;
    
        return retVal;
    }
    
    0 讨论(0)
提交回复
热议问题