来自 BufferedReader 的字符串不拆分?
String from BufferedReader not splitting?
现在我正在为一个游戏编写一个小的聊天记录插件,我想在其中保存所有消息和它在文件中发送的时间,它工作得很好,但在阅读它时我有点问题。
变量:
history = new HashMap<Date, String>();
这是我加载消息的方式:
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
(§c 和 §6 是 API 中的颜色代码,我在 Minecraft 中使用 SpigotAPI)
字符 .
是一个 特殊字符 ,如果您想使用点作为分隔符来拆分 String
,则需要使用2 个反斜杠如下:
if (date.split(",")[0].split("\.").length == 0) continue;
确实记住方法 split(String regex)
expects a regular expression 作为参数。
现在我正在为一个游戏编写一个小的聊天记录插件,我想在其中保存所有消息和它在文件中发送的时间,它工作得很好,但在阅读它时我有点问题。
变量:
history = new HashMap<Date, String>();
这是我加载消息的方式:
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
(§c 和 §6 是 API 中的颜色代码,我在 Minecraft 中使用 SpigotAPI)
字符 .
是一个 特殊字符 ,如果您想使用点作为分隔符来拆分 String
,则需要使用2 个反斜杠如下:
if (date.split(",")[0].split("\.").length == 0) continue;
确实记住方法 split(String regex)
expects a regular expression 作为参数。