繁体   English   中英

如何从 java 中的 JSON 文件加载保存的项目

[英]How to load saved item from JSON file in java

我正在制作一个应用程序,用户可以根据自己的方便更改theme (dark and light mood) 并且用户选择的theme将被保存,并且稍后再次打开应用程序时保存的theme将在那里。

我已使用JSON将数据保存到文件中。 并且当用户点击theme更改按钮时,数据将被写入file

主题代码:

private void darkTheme() {
    FlatDarkLaf.setup(); 
    UIManager.put("TextField.foreground", new ColorUIResource(Color.WHITE));
    UIManager.put("Label.foreground", new ColorUIResource(Color.WHITE));
    UIManager.put("Button.foreground", new ColorUIResource(Color.WHITE));               
    SwingUtilities.updateComponentTreeUI(contentPane);
    for(int i=0; i<arList.size(); i++) {
        ((JLabel)arList.get(i).getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
    }
}

主题代码更改并写入文件按钮:

btnDark.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String path = "resources/config.cfg";
            JSONObject json = new JSONObject();
            try {
                json.put("Theme", "darkTheme();");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
     
            try (PrintWriter out = new PrintWriter(new FileWriter(path))) {
                out.write(json.toString());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            darkTheme();
        }
    });

我可以读取文件但无法Load保存数据。 这里是读取文件的代码:

private void readData() {
    try {
    String path = "resources/config.cfg";
        InputStream is = Button.class.getResourceAsStream(path);
        if (is == null) {
            throw new NullPointerException("Cannot find resource file " + path);
        }
        JSONTokener tokener = new JSONTokener(is);
        JSONObject object = new JSONObject(tokener);
       // object.getString("darkTheme();");
        object.getJSONObject("Theme");
    }
    catch (Exception e) {
        
    }
}

谁能帮助我如何正确地做到这一点。

好的,我自己和某人的想法终于有了解决方案。 我已经更改了btnDark中的行

json.put("Theme", "darkTheme();");

json.put("Theme", "Dark");

readData()方法中我这样写

private void readData() {
    String jsonText;
    
    try {
        String path = "resources/config.cfg";
        jsonText = IOUtils.toString(new FileInputStream(new File(path)));
        int i = jsonText.indexOf("{");
        jsonText = jsonText.substring(i);
        JSONObject ob = new JSONObject(jsonText);
        String Theme = ob.getString("Theme");
        if(Theme.equals("Dark")) {
            darkTheme();
        }
        else if(Theme.equals("Light")) {
            lightTheme();
        }
        
    }catch(Exception ex) {
        ex.printStackTrace();
    }
}

现在它完美地工作了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM