今天在做項目的時候發現一個奇怪的問題
1 File file = new File("d:\\a.txt"); 2 BufferedReader br = new BufferedReader(new FileReader(file)); 3 4 String text = ""; 5 while ((text = br.readLine()) != null) { 6 7 String[] s = text.split("|"); 8 for (int i = 0; i < s.length; i++) { 9 System.out.print("切割字符串" + s[i] + "\t"); 10 } 11 System.out.println(); 12 } 13 br.close();
運行的結果
發現每一個字符都給我切割了,后來在網上查到,當以 | 切割的時候一定要注意使用轉義字符
1 File file = new File("d:\\a.txt"); 2 BufferedReader br = new BufferedReader(new FileReader(file)); 3 4 String text = ""; 5 while ((text = br.readLine()) != null) { 6 7 String[] s = text.split("\\|"); 8 for (int i = 0; i < s.length; i++) { 9 System.out.print("切割字符串" + s[i] + "\t"); 10 } 11 System.out.println(); 12 } 13 br.close();
搞定收工~