Accessing files with spaces in filename from Java

前端 未结 6 815
小鲜肉
小鲜肉 2020-11-27 23:29

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 . irea

相关标签:
6条回答
  • 2020-11-27 23:52

    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.

    0 讨论(0)
  • 2020-11-27 23:54

    Try converting it to a URL

    URL url = file.toURI().toURL();
    
    0 讨论(0)
  • 2020-11-28 00:03

    if u are taking input as a file path the try using sc.nextline() to read white spaces

    0 讨论(0)
  • 2020-11-28 00:04

    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.

    0 讨论(0)
  • 2020-11-28 00:09

    decode the path, just like this

    String decodedPath = URLDecoder.decode(path, "UTF-8");
    
    0 讨论(0)
  • 2020-11-28 00:11

    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")
    
    0 讨论(0)
提交回复
热议问题