2014-10-08 77 views
1

如何使用java中的spring註釋從類路徑加載甚至自動裝入.json文件?在子類如何在Java中使用註釋加載甚至自動裝入類路徑中的.json文件?

public abstract class ResourceLoadingTest { 

     @Rule public TestName testName = new TestName(); 

     protected String loadResource(String fileName) throws IOException { 
      final URL resource = getClass().getResource(fileName); 
      if (resource == null) { 
       throw new IllegalArgumentException("No resource file named <" + fileName + "> could be loaded from the classpath."); 
      } 

      return Resources.toString(resource, Charsets.UTF_8); 
     } 

     /** 
     * Loads a JSON resource whose name is derived from the currently running 
     * test. The derived reosurce name is "[test-method-name].json". 
     * For example, if this method is called from a test method named 
     * <code>testSomeBehavior</code>, then the resource name to be loaded will 
     * be <code>testSomeBehavior.json</code> 
     */ 
     protected String loadCurrentTestJSON() throws IOException { 
      return loadResource(testName.getMethodName() + ".json"); 
     } 

     /** 
     * Loads a XML resource whose name is derived from the currently running 
     * test. The derived reosurce name is "[test-method-name].xml". 
     * For example, if this method is called from a test method named 
     * <code>testSomeBehavior</code>, then the resource name to be loaded will 
     * be <code>testSomeBehavior.xml</code> 
     */ 
     protected String loadCurrentTestXML() throws IOException { 
      return loadResource(testName.getMethodName() + ".xml"); 
     } 
    } 

然後:

//Something like this in my controller in STS: 
@value("file:/resources/json/myJsonfile.json") 
Resource jsonTemplateFile; 
+0

感謝Ashok G.您的建議非常完美。 – Richard 2014-10-08 20:30:08

回答

-1

創建一個抽象類

public static void main(String[] args){ 
     loadSetupMessage("myJsonfile.json"); 
    } 

    protected void loadSetupMessage(String fileName) throws IOException { 
     String rawMessage = this.loadResource(fileName); 
     System.out.println(String.format("loaded class %s", rawMessage); 
    } 

和地點myJsonfile.json在同一個包層次。

相關問題