javapath-separator

Do I need to escape a separator character in a file path in java


There are many questions on escape characters but I seem unable to find an answer when using File.separator

I am using a system dependant separator character which I am creating with this code:

public class SeparatorCharactor
{
    public static String createSeparatorCharactor()
    {
        String sep = File.separator;
        return sep;
        //I could use *return File.separator;* but I prefer to do it in 2 steps.
    }
}

My understanding is that this creates a file separator that will work on any operating system.

I am then using the file separator like this :

private String sep = SeparatorCharactor.createSeparatorCharactor();
private String path = "S:"
   + sep + "folder1"
   + sep + "folder2";

My Question is : Do I need to escape the file separator ?

In other words do I need :

  1. "S" + sep + "folder1"

or

  1. "S" + sep + sep + "folder1"

Solution

  • Do I need to escape the file separator ?

    No, you do not need to escape the separator in a path in Java.

    Just use the forward-slash character (/) to indicate a file path separator in a generic sense.

    The file-related libraries in Java automatically translate the forward-slash character to the platform-specific character.

    The / translates to:


    do I need : "S" + sep + "folder1" or "S" + sep + sep + "folder1"

    Neither.

    In modern Java, use the convenient classes provided by NIO. See Path.of or Paths.get.

    Path path = Path.of( "S", "folder1" , "folder2" );
    

    separator character which I am creating with this code

    No, do not create a method for that purpose. Your method adds no value. Calling that method will only confuse anyone reading your code.

    If you want to use a constant provided by the JVM, just use it. Just call File.separator directly.


    Tip: Be careful in selecting a tutorial or article about file-handling in Java.

    The early versions of Java had file-related classes that were awkward and confusing. Many pages were written in trying to explain these. Avoid such outdated material.

    Those legacy file-handling classes were supplanted by the modern classes of NIO and NIO.2. Focus on these classes when studying Java.