2017-03-04 39 views
0

我有以下java代碼,它從資源文件夾中讀取config.properties從資源文件夾讀取conf文件時出現意外的結果

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
  • 哎出事了:空
  • 哎出事了:空
  • 哎出事了:空

它給我重新(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

能否請你解釋這種現象?

回答

0

因爲輸入流只能使用一次,所以在靜態的情況下它只能被初始化一次,並且你在第一次迭代中被使用,但是在非靜態的情況下,每次創建一個新的實例時總是被創建爲新的。

+0

消耗?它是否像隊列一樣工作(即在使用後它會被刪除) –

+0

不是你在第一次迭代中使用它的隊列。一旦你使用它,你不能再簡單地使用它。你需要重新設置,如果你想讀一遍 –

+0

的,你需要將其標記爲第一 –

相關問題