Accessing files with spaces in filename from Java
I want to access files in a directory which have spaces in filename from a java program but it doesnot access file.
Scenario is i have names of file in a file . iread file names from that file and not able to open files with spaces in java .
We are us开发者_如何学Pythoning File.exist function to check if file exist but it return false.
i have tried several kind of formats to represent spaces llike "ab\ c"for file name ab c and ab%20c for same file.
but nothing is helping.
This works fine for me. I do not escape them at all.
System.out.println(new File("/tmp/test 1/").exists());
Ensure you are useing the correct file separator for your operating system.
System.getProperty("file.separator")
decode the path, just like this
String decodedPath = URLDecoder.decode(path, "UTF-8");
Well I've never had problems with spaces in filenames while reading through Java. Just make sure you escape the path separator properly. I hope the filenames, if you're about to print out using Java, resolve to existing files with proper access permissions.
Try converting it to a URL
URL url = file.toURI().toURL();
I had the similar problem while trying to read a resource location from Servlet on a Windows OS. 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 line the verLocation.exists() is returning true else was also false.
if u are taking input as a file path the try using sc.nextline()
to read white spaces
精彩评论