OSDN Git Service

コメント追記。
[mikutoga/TogaGem.git] / src / main / java / jp / sourceforge / mikutoga / corelib / WinFile.java
1 /*
2  * Windows File utils
3  *
4  * License : The MIT License
5  * Copyright(c) 2010 MikuToga Partners
6  */
7
8 package jp.sourceforge.mikutoga.corelib;
9
10 /**
11  * Windowsに特化したFileユーティリティ。
12  */
13 public final class WinFile {
14
15     /** パスセパレータ。 */
16     public static final char SEPARATOR_CHAR = '\\';  // \
17     /** パスセパレータ文字列。 */
18     public static final String SEPARATOR =
19             Character.toString(SEPARATOR_CHAR);
20     /** UNC 分離文字列。 */
21     public static final String PFX_UNC =
22             SEPARATOR + SEPARATOR;                   // \\
23
24     static{
25         assert '\\' == 0x005c;
26     }
27
28     /**
29      * 隠しコンストラクタ。
30      */
31     private WinFile(){
32         assert false;
33         throw new AssertionError();
34     }
35
36     /**
37      * Windowsファイル名の正規化を行う。
38      * UNCも考慮される。
39      * 相対パスは相対パスのまま。
40      * <ul>
41      * <li>頭の3回以上連続する\記号は2個の\記号に置き換えられる。
42      * <li>末尾の1回以上連続する\記号は削除。
43      * ただし頭から連続している場合は削除しない。
44      * <li>2回以上連続する\記号は1個の\記号にまとめられる。
45      * ただし頭から連続している場合はまとめない。
46      * </ul>
47      * @param seq 対象ファイル名
48      * @return 正規化されたファイル名
49      */
50     public static String normalizeWinFileName(CharSequence seq){
51         String text = seq.toString();
52         text = text.replaceAll("^\\\\{3,}", "\\\\\\\\");
53         text = text.replaceAll("(.*[^\\\\])\\\\+$", "$1");
54         text = text.replaceAll("([^\\\\])\\\\{2,}", "$1\\\\");
55         return text;
56     }
57
58 }