zoukankan      html  css  js  c++  java
  • java 读取src下的配置文件

       很多时候,我们都将配置文件放在eclipse的src目录下,这个位置,相当于,当导出可执行jar包后,配置文件放在和jar同级的目录中,比如jar包放在/opt目录下,则配置文件放在/opt下,则jar包就可以读取配置文件中的内容。此时,java代码中可以通过

       String path=CommonOperation.class.getResource("/").getPath();  

       FileInputStream fin = new FileInputStream(path+"Config.properties");

    来读取配置文件。

        但要注意,用这种方法在eclipse下调试程序的时候,会发现使用setProperty(String  key ,String value)无法修改配置文件的内容,原因是 eclipse在编译文件时,已经把配置文件复制到工程的bin目录下了,修改其实已经保存在bin目录下的那个配置文件里面了。

    java读取配置文件内容的代码如下:

     String path=CommonOperation.class.getResource("/").getPath();
     InputStream fis = new FileInputStream(path+"Config.properties");
     Properties prop = new Properties();
     prop.load(fis);
     fis.close();
     return prop.getProperty(key);

    java修改配置文件内容的代码如下:

    Properties props = new Properties();
    String path=CommonOperation.class.getResource("/").getPath();
    FileInputStream fin = new FileInputStream(path+"Config.properties");
    props.load(fin); //load file
    fin.close();

    props.setProperty(key,value);
    OutputStream fout = new FileOutputStream(path+"Config.properties");
    props.store(fout, "dd");//save file
    fout.close();

  • 相关阅读:
    ZOJ 1002 Fire Net
    Uva 12889 One-Two-Three
    URAL 1881 Long problem statement
    URAL 1880 Psych Up's Eigenvalues
    URAL 1877 Bicycle Codes
    URAL 1876 Centipede's Morning
    URAL 1873. GOV Chronicles
    Uva 839 Not so Mobile
    Uva 679 Dropping Balls
    An ac a day,keep wa away
  • 原文地址:https://www.cnblogs.com/dfyz/p/4984898.html
Copyright © 2011-2022 走看看