Read file with whitespace in its path using Java

后端 未结 4 822
春和景丽
春和景丽 2020-12-03 18:42

I am trying to open files with FileInputStream that have whitespaces in their names.

For example:

String fileName = \"This is my file.txt\";
String          


        
4条回答
  •  星月不相逢
    2020-12-03 18:47

    Normally whitespace in path should't matter. Just make sure when you're passing path from external source (like command line), that it doesn't contain whitespace at the end:

    File file = new File(path.trim());
    

    In case you want to have path without spaces, you can convert it to URI and then back to path

    try {
        URI u = new URI(path.trim().replaceAll("\\u0020", "%20"));
        File file = new File(u.getPath());
    } catch (URISyntaxException ex) {
        Exceptions.printStackTrace(ex);
    }
    

提交回复
热议问题