Java reads a file with a space in its path

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

For instance:

String fileName = "This is my file.txt"; String path = "/home/myUsername/folder/"; String filePath = path + filename; f = new BufferedInputStream(new FileInputStream(filePath)); 

As a result, a FileNotFoundException is thrown. I tried to make hardcode filePath "/home/myUserName/folder/This\\ is\\ my\\ file.txt" just to see if I should avoid whitespace and it doesn't seem to work. Any suggestions on this?

EDIT: just to be on the same page with everyone looking at this question ... opening a file without spaces in its name works, which has spaces. Permissions here are not a problem and a folder delimiter.

+6
source share
4 answers

The 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() always returns true without problems

+3
source

It looks like you have a problem with the file delimiter rather than with spaces in the file names. Have you tried using

 System.getProperty("file.separator") 

instead of your '/' in a variable path?

+1
source

No, you do not need to hide the spaces.

If the code raises a FileNotFoundException , then the file does not exist (or perhaps you do not need the necessary permissions to access it).

If the permissions are right, and you think the file exists, make sure that it calls what you think it called. In particular, ensure that the file name does not contain any non-printable characters, unintended leading or trailing spaces, etc. ls -b may be useful for this.

0
source

Usually spaces along the way don't matter. Just make sure that when you pass the path from an external source (for example, the command line) so that it does not contain spaces at the end:

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

If you want to have a path with no spaces, you can convert it to a URI and then go back to the path

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

Source: https://habr.com/ru/post/907563/


All Articles