Java read file with whitespace in its path

Deadly 提交于 2019-11-28 00:33:20

问题


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

For example:

String fileName = "This is my file.txt";
String path = "/home/myUsername/folder/";

String filePath = path + filename;
f = new BufferedInputStream(new FileInputStream(filePath));

The result is that a FileNotFoundException is being thrown. I tried to hardcode the filePath to "/home/myUserName/folder/This\\ is\\ my\\ file.txt" just to see if i should escape whitespace characters and it did not seem to work. Any suggestions on this matter?

EDIT: Just to be on the same page with everyone viewing this question...opening a file without whitespace in its name works, one that has whitespaces fails. Permissions are not the issue here nor the folder separator.


回答1:


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




回答2:


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?




回答3:


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.




回答4:


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);
}


来源:https://stackoverflow.com/questions/9128288/java-read-file-with-whitespace-in-its-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!