如何关闭此文件编写器? (Java,Bukkit)

时间:2014-04-17 10:16:50

标签: java plugins bukkit

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

嘿伙计们,我知道这可能听起来很吵,但我该如何关闭这个FileWriter。代码在java中。我有一个onDisable()方法在服务器停止时调用,但是当我放置fw.close();时它会显示fw cannot be resolved。请帮忙!

代码的相关部分是

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
    }

编辑:修正:D

2 个答案:

答案 0 :(得分:1)

尝试在任何方法之外创建FileWriter,然后将其设置为onEnable()中的内容...以下是一个示例:

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();
        }
    }
}

答案 1 :(得分:0)

试试这个..

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
}
}