Java Puzzlers筆記--puzzle 21: What's my Class, take 2 路徑字符問題

package com.javapuzzlers;
import java.io.File;
public class MeToo{
   public static void main(String[] args){
      System.out.println(MeToo.class.getName().replaceAll("//.", File.separator) + ".class");
   }
}

Solution:

               顯示:(在windows中)編譯錯誤

    由於File.separator的字符在windows中是“/”,而“/”有是轉義字符的開始,所以程序認爲println的字符串中有轉移字符的存在;

TID:

        When you run the program on windows, the replacement string is a lone backslash character.

        Also, regular expressions are tricky: Problems tend to show up at run time rather than compile time;

Correctly:

       System.out.println(MeToo.class.getName().replaceAll("//.", Matcher.quoteReplacement(File.separator)) + ".class"); 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章