I’m getting this really annoying error. I’ve been working on it for days, as well as extreme amounts of research with no success. Basically, what the code is doing, is it reads the file, but it seems to remove the text after reading it. And only certain lines. This is my Reader method:
synchronized public static String getValue(String path, String filename, Boolean useColors, String folder){
try{
while(!TxtWriter.isResting());
FileRequest req = writer.getRelitive(filename, path);
if(req==null){
File f = new File(Conquest.FilePaths+"/"+folder, filename);
if(!f.getParentFile().exists())f.getParentFile().mkdirs();
if(f.exists()){
BufferedReader in = new BufferedReader(new FileReader(f));
String a;
while((a=in.readLine())!=null){
if(a.startsWith("'"+path+"'"+":")){
in.close();
a=a.substring(path.length()+3);
if(useColors)a=colorCoder(a);
return a;
}
}
in.close();
}else TxtWriter.createFile(filename, folder);
}else return ((useColors)?colorCoder(req.getMessage()):req.getMessage());
}catch(Exception e){
System.err.println("[Conquest/TxtReader] Error reading file "+filename+"!");
e.printStackTrace();
}
return null;
}
This is the file before reading:
'Kingdom':Devonel
'Flags':Leader
I call the method
public String getPlayerKingdom(String p){
String in = TxtReader.getValue("Kingdom", p+".txt", false, "Citizens");
return ((in==null)?in:"None");
}
It returns “None”, and the file now just has 'Flags':Leader, and nothing else.
What really puzzles me and certain methods work, while other don’t. Even when they are exactly the same code, but with different strings. This method right here is the same thing, but works just as its supposed to.
public int getResource(String kingdom, String name){
String out = TxtReader.getValue("R-" + name, kingdom + ".txt", false, "Kingdoms");
if(out==null)return 0;
return Integer.valueOf(out);
}
If anyone could help, I’d be thankful. 🙂
This line looks wrong:
Shouldn’t it be the other way around?
I’m not a fan of the ternary operator construct for this very reason. Just use an if/else block and be clear about what you’re doing.
Also, a BufferedReader will not remove information from a File. Period. It just reads in information and nothing else. If a line is being deleted, there’s likely another bug in your program, possibly in code not shown that is causing this.
But regardless of the source of your error, your code looks very inefficient and error-prone. Why are you trying to re-read the File each time you need to check for a match? Why not simply read the file in once, and then store the information in a
HashMap<String, String>?