Read file with whitespace in its path using Java

后端 未结 4 814
春和景丽
春和景丽 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);
    }
    
    0 讨论(0)
  • 2020-12-03 18:48

    File name with space works just fine

    Here is my code

    File f = new File("/Windows/F/Programming/Projects/NetBeans/TestApplications/database prop.properties");
            System.out.println(f.exists());
            try
            {
                FileInputStream stream = new FileInputStream(f);
            }
            catch (FileNotFoundException ex)
            {
                System.out.println(ex.getMessage());
            }
    

    f.exists() returns true always without any problem

    0 讨论(0)
  • 2020-12-03 18:52

    No, you do not need to escape whitespaces.

    If the code throws FileNotFoundException, then the file doesn't exist (or, perhaps, you lack requisite permissions to access it).

    If permissions are fine, and you think that the file exists, make sure that it's called what you think it's called. In particular, make sure that the file name does not contain any non-printable characters, inadvertent leading or trailing whitespaces etc. For this, ls -b might be helpful.

    0 讨论(0)
  • 2020-12-03 19:10

    Looks like you have a problem rather with the file separator than the whitespace in your file names. Have you tried using

    System.getProperty("file.separator")
    

    instead of your '/' in the path variable?

    0 讨论(0)
提交回复
热议问题