Ignore the arguments being passed into the method. My code:
public static void setEnabled(EntityPlayer p, Boolean b){
try{
FileReader fileReader = new FileReader(SLInfo.STORAGEFILE);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(SLInfo.STORAGEFILE);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line = null;
boolean breakearly = false;
bufferedWriter.write("HeLlo");
bufferedWriter.newLine();
bufferedWriter.write("World!");
System.out.println("GOT TO THIS FRICKIN POINT");
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
Thread.sleep(2000);
}
bufferedReader.close();
bufferedWriter.close();
}catch(Exception e){e.printStackTrace();}
}
This is simply outputting "GOT TO THIS FRICKIN POINT" (I decided this string in my fury). I have no idea why. In my file, it shows:
"Hello"
"World"
I just don't get it.
EDIT: Cool. I didn't know that. Unfortunately, that was just a simple example that I thought would solve my problem... it didn't. Taking a look at my code below, and assuming that the file contains p.username, which is a string, on line 1, why is "got here" never printed and "did this" always printed. What I expected it to do: If p.username is on line x, it changes line x to read "p.username booleanvalue" and if p.username is not anywhere in the file, "p.username booleanvalue" is appended to the last line in the file.
public static void setEnabled(EntityPlayer p, Boolean b){
try{
FileReader fileReader = new FileReader(SLInfo.STORAGEFILE);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(SLInfo.STORAGEFILE);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line = null;
boolean breakearly = false;
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
if (line.contains(p.username)){
System.out.println("Got here");
bufferedWriter.write(p.username + " " + Boolean.toString(b));
bufferedWriter.newLine();
bufferedWriter.flush();
breakearly = true;
break;
}
}
bufferedWriter.flush();
System.out.println(breakearly);
if (!breakearly){
System.out.println("did this");
bufferedWriter.write(p.username + " " + Boolean.toString(b));
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedReader.close();
bufferedWriter.close();
}catch(Exception e){e.printStackTrace();}
}
(Yes, I know I have excessive flushes)
This is where the Buffered in BufferedWriter comes in.
You write two lines, which due to buffering are stored in memory.
You then read from the file, which has nothing written to it yet.
Then you close the writer, causing the buffers to flush, adding the contents to the file.
To force flushing before you read, you can use bufferedWriter.flush(), or close it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With