【问题标题】:Get settings from a text file in Java从 Java 中的文本文件获取设置
【发布时间】:2012-07-31 10:58:33
【问题描述】:

我正在使用 Eclipse,并且我在 mi src 文件夹之外创建了一个 res 文件夹。在其中,我创建了一个名为“config.cfg”的文本文件。看起来像这样:

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

radiomodemPort=20001

sisnetPort=5562

sisnetHost=213.229.135.3

sisnetUser=jogg

sisnetPass=jogg

为读取它而编写的代码不起作用:它不会加载任何存储的变量。我的代码是:

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

怎么了?

【问题讨论】:

  • 尝试使用System.out.println(new File("res/config.cfg").getAbsolutePath()); 并确认您确实获得了正确的文件。另外,你为什么要循环它而不是只做sisnetHost = config.get("&lt;key&gt;");等?
  • 尝试执行此操作 config.load(new FileInputStream("res/config.cfg")); System.out.println(config);结果如何?
  • 首先尝试检查您提供的文件位置是否正确。你可以在 catch 部分尝试一些 print 语句来了解它是否真的抛出了一些错误。
  • @Thor84no 主要问题是 Costi 指出的:真是错过了!无论如何,感谢您对如何在没有循环的情况下改进代码的建议

标签: java properties resources settings


【解决方案1】:

在您的equals 测试中,您将每个键与您的实例变量(似乎有默认值:null 用于对象,0 用于数字等)进行比较。使用实际的字符串来测试键:

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

通常建议在文字/常量上调用equals,以消除 NPE 的风险:

if ("sisnetHost".equals(key))

【讨论】:

    【解决方案2】:

    这里准备好了静态类

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

    这里是示例:

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

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 2023-03-30
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多