Right now I'm programming a little chat history plugin for a game, in which I want to save all messages and the time it was sent in a file, which is working perfectly, but when reading it I'm getting a little problem. variables: history = new HashMap<Date, String>();
This is how I load the messages:
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();
}
}
This is what I have written in the file:
09.01.17,18:45:26 §6[RoflFrankoc] §cHi
09.01.17,18:45:30 §6[RoflFrankoc] §cHello world
Now my problem: The line if (date.split(",")[0].split(".").length == 0) continue;
is stopping the lines from getting added to history
. Without it I get an ArrayOutOfBoundsError: 0. with these lines
for (int i = 0; i < line.split(" ").length; i++){
System.out.print(i+"="+line.split(" ")[i]+" ");
}
I'm checking if it's reading correctly, which yes it is, output:
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
(The §c's and §6's are color codes in the API, I'm using the SpigotAPI for Minecraft)
The character .
is a special character , if you want to split your String
using a dot as separator, you need to escape it with 2 backslashes as next:
if (date.split(",")[0].split("\\.").length == 0) continue;
Indeed keep in mind that the method split(String regex)
expects a regular expression as argument.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.