首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于ini4j的单例模式

基于ini4j的单例模式
EN

Stack Overflow用户
提问于 2016-12-25 16:06:09
回答 1查看 400关注 0票数 1

原始问题:程序正在读取旧配置文件(.ini)的输入。

新问题:在尝试使用流/ini的单例模式后,我无法再写入文件。它抛出了一个java.io.FileNotFoundException。

无论如何,我是否可以修改我的配置类以使其工作?

提前谢谢。

配置类:

代码语言:javascript
复制
import org.ini4j.Wini;
import java.io.*;

//http://www.javenue.info/post/40

public class Configuration {
    private static Configuration _instance = null;

    private Wini ini = null;
    FileInputStream stream;

    private Configuration() {
        ini= new Wini();
        try {
            stream = new FileInputStream(Constants.PATH);
            ini.load(stream);
        }
        catch (Exception e) {
            System.out.println("FILE NOT FOUND!");
        }
    }

    public synchronized static Configuration getInstance() {
        if (_instance == null)
            _instance = new Configuration();
        return _instance;
    }

    public String getConfig(String xSectionName, String xFieldValue){

        String readValue = null;

        if (ini.get(xSectionName, xFieldValue) != null) {
            readValue = ini.get(xSectionName, xFieldValue);
        } else {
            // TODO: What should happen
        }
        return readValue;
    }

    public void setConfig(String xSectionName, String xFieldValue, String xValue){

        System.out.println("Section: " + xSectionName);
        System.out.println("Field:   " + xFieldValue);
        System.out.println("Value:   " + xValue + "\n\n");

        try {
            ini.put(xSectionName, xFieldValue, xValue);
            ini.store();
        } catch (Exception e1) {
            System.out.println(xValue + " could not be stored.");
            e1.printStackTrace();
        }
    }
}

部分:漂移 领域:亩 价值:5 5不能保存。 application.prototypes.Configuration.setConfig(Configuration.java:72),application.prototypes.UserInputs.lambda$0(UserInputs.java:92),com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86),com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238),com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:,java.io.FileNotFoundException at org.ini4j.Ini.store在com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun。javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Scene$KeyHandler.process(Scene.java:3964) at javafx.scene.( javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040) at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2501) at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:216) at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:148) at java.security.AccessController.doPrivileged(Native Method)在com.sun.javafx.tk。quantum.GlassViewEventHandler.lambda$handleKeyEvent$353(GlassViewEventHandler.java:247) at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389) at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:246) at com.sun.glass.ui.View.handleKeyEvent(View.java:546) at com.sun.glass.ui.View.notifyKey(View.java:966) at com.sun.glass.ui.win.WinApplication._runLoop(本机方法)在com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191) at java.lang.Thread.run(未知来源)

关于新问题的决议:见下文的答案。

对原问题的解决:

我用库动态地加载了一个类。经过一些研究,我读到ClassLoader只能有一个特定类的实例。因此,解决方案是在ClassLoader ()方法中创建一个新的.loadFromJava实例,并解决boom问题。

下面是一些代码。

代码语言:javascript
复制
import net.openhft.compiler.CompilerUtils;

...

ClassLoader classloader = new ClassLoader() {
        };

Class aClass = CompilerUtils.CACHED_COMPILER.loadFromJava(classloader, className, javaCode);

Callable<Object[]> caller = (Callable<Object[]>) aClass.newInstance();

Object[] obj = (Object[]) caller.call();

...

动态类实现可调用并返回对象--因此可以检索在其中创建的任何内容。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-25 16:51:06

我刚刚查看了源代码。

问题是,如果您想使用同一个void load(InputStream input)实例来调用store()方法,则应该避免Wini类中的Wini加载ini文件。

为什么?因为store()方法希望在当前Wini的实例中有一个现有的文件字段,但是它找不到它,因为您已经从流而不是文件加载了ini。

因此,您应该使用Wini构造函数加载ini文件。构造函数以File作为参数,它还将实例中的字段设置为加载ini内容。

看看这个:

代码语言:javascript
复制
public Wini(File input) throws IOException, InvalidFileFormatException{
        this();
        setFile(input);
        load();
}

因此,替换:

代码语言:javascript
复制
 private Configuration() {
        ini = new Wini();
        try {
            stream = new FileInputStream(Constants.PATH);
            ini.load(stream);
        }
        catch (Exception e) {
            System.out.println("FILE NOT FOUND!");
        }
    }

通过这一点:

代码语言:javascript
复制
private Configuration()  {
    try {
        ini= new Wini(new File(Constants.PATH));
    }
    catch (Exception e) {
        LOGGER.error("Exception during init of Configuration",e);
    }
}

下面是使用日志记录异常的完整类,它使用延迟的单例实现,而不使用任何显式同步作为synchronized

代码语言:javascript
复制
public class Configuration {

    private static Logger LOGGER = Logger.getLogger(Configuration.class)//

    private static class HolderLazySingleton {
        private static Configuration instance = new Configuration();
    }

    private Wini ini = null;

    private Configuration() {    
        try {
            ini = new Wini(new File(Constants.PATH));    
        } catch (Exception e) {
            LOGGER.error("Exception during init of Configuration",e);
        }
    }

    public static Configuration getInstance() {
        return HolderLazySingleton.instance;
    }

    public String getConfig(String xSectionName, String xFieldValue) {

        String readValue = null;

        if (ini.get(xSectionName, xFieldValue) != null) {
            readValue = ini.get(xSectionName, xFieldValue);
        } else {
            // TODO: What should happen
        }
        return readValue;
    }

    public void setConfig(String xSectionName, String xFieldValue, String xValue) {

        System.out.println("Section: " + xSectionName);
        System.out.println("Field:   " + xFieldValue);
        System.out.println("Value:   " + xValue + "\n\n");

        try {
            ini.put(xSectionName, xFieldValue, xValue);
            ini.store();
        } catch (Exception e1) {
            LOGGER.error(xValue + " could not be stored.", e1);         
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41322630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档