posts - 35, comments - 0, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

File.separator

Posted on 2012-07-10 17:12 timelyxyz 阅读(148) 评论(0)  编辑  收藏

API语法:

File(String pathname)
通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。
public static final String separator
与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串。此字符串只包含一个字符,即 separatorChar
public static final char separatorChar
与系统有关的默认名称分隔符。此字段被初始化为包含系统属性 file.separator 值的第一个字符。在 UNIX 系统上,此字段的值为 '/';在 Microsoft Windows 系统上,它为 '\\'

注意:

路径名字符串与抽象路径名之间的转换与系统有关。将抽象路径名转换为路径名字符串时,每个名称与下一个名称之间用一个默认分隔符 隔开。默认名称分隔符由系统属性 file.separator 定义,可通过此类的公共静态字段 separatorseparatorChar 使其可用。将路径名字符串转换为抽象路径名时,可以使用默认名称分隔符或者底层系统支持的任何其他名称分隔符来分隔其中的名称。

 

例如,我希望的文件绝对路径是E:\dev\workspace\iclass_web/conf/filterconfig.xml(计作myPath),有两种创建File的形式:

1)new File(myPath)不会报错;

2)new File("E:\dev\workspace\iclass_web/conf/filterconfig.xm")报错,应修改为new File("E:\\dev\\workspace\\iclass_web/conf/filterconfig.xml"

 我的系统是windows32位,io.File的一个字段FileSystem是一个抽象类,FileSystem被一个Win32FileSystem类继承,从而实现里面的public abstract String normalize(String path);方法。

 Win32FileSystem部分源码如下:

 1 private final char slash;  2     private final char altSlash;  3     private final char semicolon;  4
 5     public Win32FileSystem() {  6     slash = ((String) AccessController.doPrivileged(  7               new GetPropertyAction("file.separator"))).charAt(0);  8     semicolon = ((String) AccessController.doPrivileged(  9               new GetPropertyAction("path.separator"))).charAt(0); 10     altSlash = (this.slash == '\\') ? '/' : '\\'; 11     } 12 13     private boolean isSlash(char c) { 14     return (c == '\\') || (c == '/'); 15     } 16 17     private boolean isLetter(char c) { 18     return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')); 19     } 20 21     private String slashify(String p) { 22     if ((p.length() > 0) && (p.charAt(0) != slash)) return slash + p; 23     else return p; 24     } 25    26     /* Check that the given pathname is normal.  If not, invoke the real 27        normalizer on the part of the pathname that requires normalization. 28        This way we iterate through the whole pathname string only once. */ 29     public String normalize(String path) { 30     int n = path.length(); 31     char slash = this.slash; 32     char altSlash = this.altSlash; 33     char prev = 0; 34     for (int i = 0; i < n; i++) { 35         char c = path.charAt(i); 36         if (c == altSlash) 37         return normalize(path, n, (prev == slash) ? i - 1 : i); 38         if ((c == slash) && (prev == slash) && (i > 1)) 39         return normalize(path, n, i - 1); 40         if ((c == ':') && (i > 1)) 41         return normalize(path, n, 0); 42         prev = c; 43     } 44     if (prev == slash) return normalize(path, n, n - 1); 45     return path; 46     }

 


只有注册用户登录后才能发表评论。


网站导航: