[英]How to make a method run only once in the lifetime of application
I have a method that fills in a file with default values and I call that method in the constructor. 我有一个用默认值填充文件的方法,然后在构造函数中调用该方法。 I want that method to run only once ( I mean by only once so when the user press the play button /in eclipse/ then that method will not run in the second press.
我希望该方法仅运行一次(我的意思是仅运行一次,因此当用户按下播放按钮/ eclipse /时,该方法将不会在第二次按下时运行。
I have tried something like this but it doesn't work : 我已经尝试过类似的方法,但是不起作用:
private boolean defaultExecuted;
public synchronized void defaultStatsFile()
{
if (defaultExecuted)
{
return;
}
else
{
fileReadNWrite.configWriter("panel1", "non-US incidents");
fileReadNWrite.configWriter("panel2", "Hoaxes");
fileReadNWrite.configWriter("panel3", "Under NUFORC investigation");
fileReadNWrite.configWriter("panel4", "Likliest Shape");
defaultExecuted = true;
}
}
Is there a smarter way to fill in a file only once ? 有没有一种聪明的方法可以只填写一次文件?
Please if something is not clear comment and I will reply. 如果有不清楚的地方请发表评论,我会回复。 Any help is appreciated.
任何帮助表示赞赏。
Better you fill data in static block 更好地将数据填充到静态块中
like : including proper exception handling in Main class , this way no need to dependent on constructor to load default data in file. 例如:在Main类中包括适当的异常处理,这种方式无需依赖构造函数将默认数据加载到文件中。
static {
fileReadNWrite.configWriter("panel1", "non-US incidents");
fileReadNWrite.configWriter("panel2", "Hoaxes");
fileReadNWrite.configWriter("panel3", "Under NUFORC investigation");
fileReadNWrite.configWriter("panel4", "Likliest Shape");
defaultExecuted = true;
}
因为所有代码都在类中,并且您可以有多个独立类加载器,所以您无法在Java中执行此操作,因此需要Java之外的一些资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.