2017-01-09 43 views
3

现在我正在为一款游戏编写一个小聊天记录插件,在这个插件中,我想将所有消息和发送时间保存在一个完美的文件中,但是当阅读时,问题。 变量: history = new HashMap<Date, String>(); 这是我的加载消息:来自BufferedReader的字符串没有分裂?

public static void load(){ 
    File f = new File(config.getString("file")); 
    if (!f.exists()){ 
     try { 
      f.createNewFile(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    try{ 
     BufferedReader br = new BufferedReader(new FileReader(f)); 
     String line; 
     while ((line = br.readLine())!=null){ 
      String date = line.split(" ")[0]; 
      for (int i = 0; i < line.split(" ").length; i++){ 
       System.out.print(i+"="+line.split(" ")[i]+" "); 
      } 
      if (date.split(",")[0].split(".").length == 0) continue; 
      line = line.replaceAll(date+" ", ""); 
      history.put(fromString(date), line); 
     } 
     br.close(); 
    }catch(IOException e){ 
     e.printStackTrace(); 
    } 
} 

这是我写的文件中:

09.01.17,18:45:26 §6[RoflFrankoc] §cHi 
09.01.17,18:45:30 §6[RoflFrankoc] §cHello world 

现在我的问题: 线if (date.split(",")[0].split(".").length == 0) continue;被停止从添加到history的行。没有它,我得到一个ArrayOutOfBoundsError:0 这些线

for (int i = 0; i < line.split(" ").length; i++){ 
    System.out.print(i+"="+line.split(" ")[i]+" "); 
} 

我检查,如果它的正确阅读,这的确是这样,输出:

0=09.01.17,18:45:30 
1=§6[RoflFrankoc] 
2=§cHello 
3=world 
0=09.01.17,18:45:26 
1=§6[RoflFrankoc] 
2=§cHi 

(该照着的和§6的在颜色代码的API中,我使用的Minecraft的SpigotAPI)

+0

'createNewFile()'是毫无意义的。赶上'FileNotFoundException'。 – EJP

回答

5

字符.特殊字符,如果你想用一个句点分隔,Y分割您String OU需要2个反斜线旁边逃避它:

if (date.split(",")[0].split("\\.").length == 0) continue; 

事实上记住,该方法split(String regex)需要一个regular expression作为参数。