简体   繁体   中英

Get settings from a text file in Java

I'm working over Eclipse, and I have created a res folder outside mi src folder. In it, I have created a text file called "config.cfg". Looks like this:

# System configuration
# Comments will automatically be excluded by the program

radiomodemPort=20001

sisnetPort=5562

sisnetHost=213.229.135.3

sisnetUser=jogg

sisnetPass=jogg

The code written to read it is not working: it doesn't load any of the variables stored. My code is:

private String sisnetHost;
private int sisnetPort;
private int radiomodemPort;
private String sisnetUser;
private String sisnetPass;

private boolean sisnetHostLoaded;
private boolean sisnetPortLoaded;
private boolean radiomodemPortLoaded;
private boolean sisnetUserLoaded;
private boolean sisnetPassLoaded;

public boolean getSettingsFromFile(){
        Properties config = new Properties();
        try {
            config.load(new FileInputStream("res/config.cfg"));
            Enumeration<Object> en = config.keys();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                if(key.equals(sisnetHost)){
                    sisnetHost = (String)config.get(key);
                    sisnetHostLoaded = true;
                }
                if(key.equals(sisnetPort)){
                    sisnetPort = (Integer)config.get(key);
                    sisnetPortLoaded = true;
                }
                if(key.equals(sisnetUser)){
                    sisnetUser = (String)config.get(key);
                    sisnetUserLoaded = true;
                }
                if(key.equals(sisnetPass)){
                    sisnetPass = (String)config.get(key);
                    sisnetPassLoaded = true;
                }
                if(key.equals(radiomodemPort)){
                    radiomodemPort = (Integer)config.get(key);
                    radiomodemPortLoaded = true;
                }
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            return false;
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }

        if(!(sisnetHostLoaded && sisnetPortLoaded && sisnetUserLoaded && sisnetPassLoaded && radiomodemPortLoaded))
            fillUnloadedSettings();
        return true;
    }

What's wrong?

In your equals test, you're comparing each key with your instance variables (which seem to have default values: null for objects, 0 for numbers etc.). Use the actual strings to test the keys:

if(key.equals("sisnetHost")) // NOT if(key.equals(sisnetHost))

Usually it's recommended to to call equals on the literal / constant in order to eliminate the risk of a NPE:

if ("sisnetHost".equals(key))

Here ready static class

import java.io.*;
import java.util.Properties;
public class Settings {
    public static String Get(String name,String defVal){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            FileReader reader = new FileReader(configFile);
            Properties props = new Properties();
            props.load(reader);
            reader.close();
            return props.getProperty(name);
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
            return defVal;
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
            return defVal;
        } catch (Exception ex){
            logger.error(ex);
            return defVal;
        }
    }
    public static Integer Get(String name,Integer defVal){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            FileReader reader = new FileReader(configFile);
            Properties props = new Properties();
            props.load(reader);
            reader.close();
            return Integer.valueOf(props.getProperty(name));
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
            return defVal;
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
            return defVal;
        } catch (Exception ex){
            logger.error(ex);
            return defVal;
        }
    }
    public static Boolean Get(String name,Boolean defVal){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            FileReader reader = new FileReader(configFile);
            Properties props = new Properties();
            props.load(reader);
            reader.close();
            return Boolean.valueOf(props.getProperty(name));
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
            return defVal;
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
            return defVal;
        } catch (Exception ex){
            logger.error(ex);
            return defVal;
        }
    }
    public static void Set(String name, String value){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            Properties props = new Properties();
            FileReader reader = new FileReader(configFile);
            props.load(reader);
            props.setProperty(name, value.toString());
            FileWriter writer = new FileWriter(configFile);
            props.store(writer, Variables.SETTINGS_COMMENT);
            writer.close();
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
        } catch (Exception ex){
            logger.error(ex);
        }
    }
    public static void Set(String name, Integer value){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            Properties props = new Properties();
            FileReader reader = new FileReader(configFile);
            props.load(reader);
            props.setProperty(name, value.toString());
            FileWriter writer = new FileWriter(configFile);
            props.store(writer,Variables.SETTINGS_COMMENT);
            writer.close();
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
        } catch (Exception ex){
            logger.error(ex);
        }
    }
    public static void Set(String name, Boolean value){
        File configFile = new File(Variables.SETTINGS_FILE);
        try {
            Properties props = new Properties();
            FileReader reader = new FileReader(configFile);
            props.load(reader);
            props.setProperty(name, value.toString());
            FileWriter writer = new FileWriter(configFile);
            props.store(writer,Variables.SETTINGS_COMMENT);
            writer.close();
        } catch (FileNotFoundException ex) {
            // file does not exist
            logger.error(ex);
        } catch (IOException ex) {
            // I/O error
            logger.error(ex);
        } catch (Exception ex){
            logger.error(ex);
        }
    }
}

Here sample:

    Settings.Set("valueName1","value");
    String val1=Settings.Get("valueName1","value");
    Settings.Set("valueName2",true);
    Boolean val2=Settings.Get("valueName2",true);
    Settings.Set("valueName3",100);
    Integer val3=Settings.Get("valueName3",100);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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