从资源文件夹中读取conf文件时出现意外结果

时间:2017-03-04 12:48:00

标签: java

我有以下java代码,它从资源文件夹中读取config.properties

 import java.io.InputStream;
 import java.util.Properties;

    public class TestProperties {

         static ClassLoader classloader = Thread.currentThread().getContextClassLoader();
         static InputStream input = classloader.getResourceAsStream("config.properties");

        public static void main(String[] args) throws InterruptedException {
            while (true) {
                new TestProperties().readPropertiesFile();
                Thread.sleep(2000);
            }
        }

        private void readPropertiesFile() {
            Properties properties = new Properties();

            try {
                properties.load(input);
                int threads = Integer.parseInt(properties.getProperty("num_of_workers"));
                System.out.println("num_of_workers: " + threads);
            } catch (Exception e) {
                System.out.println("hey something went wrong: " + e.getMessage());
            }
        }
    }

结果:

  • num_of_workers:2
  • 嘿,出了点问题:null
  • 嘿,出了点问题:null
  • 嘿,出了点问题:null

它首先给我结果(num_of_workers: 2),但之后它给出了空

但是当我改变时

  • static ClassLoader classloaderClassLoader classloader
  • static InputStream inputInputStream input

我得到了预期的结果:

  • num_of_workers:2
  • num_of_workers:2
  • num_of_workers:2
  • num_of_workers:2

你能解释一下这种行为吗?

1 个答案:

答案 0 :(得分:0)

因为输入流只能使用一次, 在静态的情况下,它只被初始化一次并且你在第一次迭代中被消耗,但是在非静态的情况下,它总是在每次创建一个新实例时被创建为新的。

相关问题