5 Replies Latest reply: May 31, 2012 7:52 PM by EJP RSS

    Issues with file path in java.io.File

    940941
      I am getting file path in eclipse plugin using org.eclipse.swt.widgets.FileDialog and saving the path in XML files.

      In web.xml , path is stored as below (I can't change backsladh to forwardslash or escape backslash since the value is coming from SWT FileDialog)

      <init-param>
      <param-name>filePath</param-name>
      <param-value>c:\new\demo\next\version.txt</param-value>
      </init-param>

      In my filter , i have below code in init() method but am not able to get File reference due to special characters

      String filePath = filterConfig.getInitParameter("filePath");
      // Tried filePath.replace('\\','/') --> Didnot work since \n is a single character
      File f = new File(path)
        • 1. Re: Issues with file path in java.io.File
          EJP
          You don't have to replace anything. Just use the strings as is. Java will sort it out.
          • 2. Re: Issues with file path in java.io.File
            940941
            No it does not. You need to escape file paths properly. You can check this with simple code and that the problem i am facing now

                 public static void main(String[] args) {
                      String path = Messages.getString("filePath"); //in messages.properties put filePath=c:\new\next\verison.txt
                      System.out.println(path);
                      File f = new File(path);
                      System.out.println(f.exists());
                 }
            • 3. Re: Issues with file path in java.io.File
              EJP
              That's because the .properties file is itself incorrect. The properties file needs double backslashes. See the Javadoc for java.util.Properties. When it comes into Messages the backslashes have completely disappeared due to this error, so your Java code can't do anything anway. Print the filename out and see. Better still, use forward slashes and eliminate the problem completely.
              • 4. Re: Issues with file path in java.io.File
                940941
                Agreed but if you see my original question , path is stored in XML file and at this point i cannot put \\ or forward slash in xml
                • 5. Re: Issues with file path in java.io.File
                  EJP
                  If you can read the backslash from the XML into a String that contains the backslash it will work when you construct a File. If you can't read the backslash from the XML you need to do something about that, probably at the source of the XML, i.e. use forward slashes. You don't need to double backslashes in Java code. You only need to do that in Java String literals, property files, and any other file formats that require it.