Question

try {
        FileWriter fw = new FileWriter("plugins/TestMessage/messages.txt", true);
    } catch (IOException e) {
        e.printStackTrace();}
    }

Hey guys, I know this may sound noobish but how do I close this FileWriter. The code is in java. I have an onDisable() method that gets called when the server is stopped but when I put fw.close(); It says fw cannot be resolved. Please help!

The relevant section of the code is

public class MAIN extends JavaPlugin{{
    try {
        FileWriter fw = new FileWriter("plugins/TestMessage/messages.txt", true);
    } catch (IOException e) {
        e.printStackTrace();}
    }

    public void onEnable(){
        Logger.getLogger("Minecraft").info("MessageBroadcaster made by cheeseballs500 aka weakwizardsucks2");
    }

    public void onDisable(){
        fw.close();//fw cannot be resolved
    }

EDIT: Fixed :D

Was it helpful?

Solution 2

Try this..

public class MAIN extends JavaPlugin{
public MAIN() {
    try {
        this.fw = new FileWriter("plugins/TestMessage/messages.txt", true);
    } catch (Exception e) {
        // TODO: handle exception
    }

}

FileWriter fw = null;

public void onEnable(){
    Logger.getLogger("Minecraft").info("MessageBroadcaster made by cheeseballs500 aka weakwizardsucks2");
}

public void onDisable(){
    try {
        fw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }//fw cannot be resolved
}
}

OTHER TIPS

Try creating the FileWriter outside of any methods, then setting it to something in your onEnable()... Here's an example:

public class Main extends JavaPlugin{{
    FileWriter fw;//create the variable

    @Override
    public void onEnable(){
        try{
            fw = new FileWriter(this.getDataFolder() + "/messages.txt", true); //assign the variable to a value, and put the file in your plugin's folder
        }
        catch(IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void onDisable(){
        try{ //try-catch just incase
            fw.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top