Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file with whitespace in its path using Java

Tags:

java

java-io

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.

like image 334
user253530 Avatar asked Feb 03 '12 11:02

user253530


2 Answers

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

like image 166
Sunil Kumar B M Avatar answered Oct 21 '22 20:10

Sunil Kumar B M


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?

like image 22
Kris Avatar answered Oct 21 '22 20:10

Kris