Access files with spaces in file name from java

I want to access files in a directory with spaces in the file name from a java program, but it does not have access to the file.

Scenario: I have file names in a file. iread file names are from this file and cannot open files with spaces in java.

We use the File.exist function to check if a file exists, but it returns false.

I tried several formats for representing spaces, like "ab \ c" for the file name ab c and ab% 20c for the same file.

but nothing helps.

+6
java file operating-system
source share
6 answers

This works great for me. I do not avoid them at all.

System.out.println(new File("/tmp/test 1/").exists()); 

Make sure you use the correct file separator for your operating system.

 System.getProperty("file.separator") 
+10
source share

decode the path, exactly the same

 String decodedPath = URLDecoder.decode(path, "UTF-8"); 
+6
source share

Well, I never had problems with spaces in file names when reading through Java. Just make sure you escape from the path separator. I hope that the file names, if you are going to print using Java, allow existing files with the proper permissions.

+1
source share

if u accepts input as a file path, try using sc.nextline() to read spaces

+1
source share

Try converting it to URL

 URL url = file.toURI().toURL(); 
0
source share

I had a similar problem when trying to read the resource location from Servlet on Windows . The following line worked for me.

 String path = config.getServletContext().getResource("/app").toString(); path = URLDecoder.decode(path,"UTF-8"); path = path.replaceAll("file:/", ""); path = path.replaceAll("\\u0020", "\\ "); File verLocation = new File(path); 

After all of the above value returns verLocation.exists (), true is also false.

0
source share

All Articles