带有ini4j的单例模式

时间:2016-12-25 16:06:10

标签: java singleton inputstream fileinputstream

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

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

无论如何,我可以修改我的Configuration类以使其工作吗?

提前致谢。

配置类:

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

部分:漂移

     

字段:mu

     

价值:5

     

5无法存储。

     

org.ini4j.Ini.store中的java.io.FileNotFoundException(Ini.java:126)     在   application.prototypes.Configuration.setConfig(Configuration.java:72)     在application.prototypes.UserInputs.lambda $ 0(UserInputs.java:92)at   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:191)     在   com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)     在   com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)     在   com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)     在   com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)     在   com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)     在   com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)     在   com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)     在com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)     在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.Scene $ KeyHandler.access $ 1800(Scene.java:3910)at at   javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)at   javafx.scene.Scene $ ScenePeerListener.keyEvent(Scene.java:2501)at at   com.sun.javafx.tk.quantum.GlassViewEventHandler $ KeyEventNotification.run(GlassViewEventHandler.java:216)     在   com.sun.javafx.tk.quantum.GlassViewEventHandler $ KeyEventNotification.run(GlassViewEventHandler.java:148)     在java.security.AccessController.doPrivileged(Native Method)at   com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda $ handleKeyEvent $ 353(GlassViewEventHandler.java:247)     在   com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)     在   com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:246)     在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(Native Method)at   com.sun.glass.ui.win.WinApplication.lambda为$ null $ 148(WinApplication.java:191)     在java.lang.Thread.run(未知来源)

解决新问题:见下面的答案。

解决原始问题:

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

这是一些代码。

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

...

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

1 个答案:

答案 0 :(得分:1)

我刚看了一下源代码 问题是,如果要使用相同的void load(InputStream input)实例来调用Wini方法,则应该避免Winistore()加载ini文件。
为什么? 因为store()方法期望在当前Wini的实例中具有现有文件字段,但由于您从流而不是文件加载了ini,因此无法找到它。 / p>

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

看看这个:

public Wini(File input) throws IOException, InvalidFileFormatException{
        this();
        setFile(input);
        load();
}

所以替换:

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

由此:

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

以下是使用日志记录来记录异常的完整类,它使用惰性单例实现,而不使用任何显式同步synchronized

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