Forward slash or backslash?

前端 未结 4 2108
谎友^
谎友^ 2020-11-27 20:55

I am looking to write and read text files to and from (respectively) a directory different from that of my program. When I specify a directory to write to or read from, shou

4条回答
  •  独厮守ぢ
    2020-11-27 21:28

    You could use either.

    If you use / then you only need a single slash.
    If you use \, you need to use \\. That is, you need to escape it.

    You can also use the resolve() method of the java.nio.Path class to add directories / files to the existing path. That avoids the hassle of using forward or backward slashes. You can then get the absolute path by calling the toAbsolutePath() method followed by toString()

    SSCCE:

    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    public class PathSeperator {
        public static void main(String[] args) {
            // the path seperator for this system
            String pathSep = System.getProperty("path.separator");
    
            // my home directory
            Path homeDir = Paths.get(System.getProperty("user.home"));
    
            // lets print them
            System.out.println("Path Sep: " + pathSep);
            System.out.println(homeDir.toAbsolutePath());
    
            // as it turns out, on my linux it is a colon
            // and Java is using forward slash internally
            // lets add some more directories to the user.home
    
            homeDir = homeDir.resolve("eclipse").resolve("configuration");
            System.out.println("Appending more directories using resolve()");
            System.out.println(homeDir);
    
        }
    }  
    

提交回复
热议问题