2016-01-13 59 views
0

我正在測試使用屬性(mytest.properties)的庫(jar)。他們的方法庫(JAR)加載屬性是通過做更新/編輯屬性文件

   ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
       InputStream input = classLoader.getResourceAsStream("mytest.properties"); 

所以,我想測試是當地產的文件中存在發生什麼事,當它不存在。爲了測試這個,我需要在JVM啓動後編輯屬性文件。我試過這樣做,不起作用。貝婁是我試圖編輯屬性文件的代碼,但總是返回空字符串。 main_mytest.properties的

內容是:mytest.properties和empty.txt的

a=hello world 
b=hello java 

內容是空的。

"" 

我的班級是:

import org.apache.commons.io.IOUtils; 

    import java.io.IOException; 
    import java.io.InputStream; 
    import java.io.StringWriter; 
    import java.nio.file.Files; 
    import java.nio.file.Path; 
    import java.nio.file.Paths; 
    import java.nio.file.StandardCopyOption; 

    public class MyPropertyFiles { 


     final static String resourcesPath = "./mytestproj/src/main/resources"; 

     public static void main(String [] args) throws IOException { 

      Path source = Paths.get(resourcesPath + "/main_mytest.properties"); 
      Path destination = Paths.get(resourcesPath + "/mytest.properties"); 
      Path empty = Paths.get(resourcesPath + "/empty.txt"); 

      try 
      { 
       Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING); 

       ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
       InputStream input = classLoader.getResourceAsStream("mytest.properties"); 
       StringWriter writer = new StringWriter(); 
       IOUtils.copy(input, writer, "utf-8"); 
       String theString = writer.toString(); 
       System.out.println("!!!!!!!!!!!!!!!! The String: \n" + theString); 

      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 
      finally { 
       Files.copy(empty, destination, StandardCopyOption.REPLACE_EXISTING); 
      } 

     } 
    } 
+0

你確定'mytest.properties'是可寫入你當前的權限嗎?嘗試在第一個'Files.copy'語句之後放置一個調試點,並查看磁盤上文件的內容。這可能有幫助。 –

+0

文件的內容得到更新。但更新內容不在'classLoader.getResourceAsStream(「mytest.properties」);' –

+0

您正在使用的測試屬性文件可能不在您的類路徑中,這是'ClassLoader'正在查找使用你給它的名字。檢查這個答案︰http://stackoverflow.com/questions/19035407/classloader-getresourceasstream-returns-null –

回答

0

做一些挖,我不認爲重新加載文件在ClassLoader允許已啓動JVM後後。