2016-04-28 179 views
0

首先,我已经通过在eclipse和tomcat 8.0.33独立版本的mac上提取war文件(使用maven)来试用我的代码。加载资源在本地工作,但不在服务器上

我也试过我的代码在Windows服务器2008年与相同的Java版本1.8,它工作时,我把一些变量(这是用户名和密码)硬编码,但是当我让代码读取它们从一个reousrce文件,它只是我的Mac上工作(Eclipse和单独的tomcat站),而不是在服务器上

这是代码读取资源

private static String getUsername() { 
     Properties prop = new Properties(); 
     InputStream input = null; 

     try { 

      input = new FileInputStream(MyConfiguration.class.getClassLoader() 
        .getResource("configuration.properties").getFile()); 

      // load a properties file 
      prop.load(input); 

      // get the property value and print it out 
      return prop.getProperty("username"); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } finally { 
      if (input != null) { 
       try { 
        input.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     return null; 
    } 

其中configuration.properties的位置在src/main/resources和服务器上,我可以看到该文件位于正确的目录中。

我使用Maven的,我不知道你需要什么其他信息来帮助我,但如果你说,我会给你

回答

1

您可以尝试 input = Thread.currentThread().getContextClassLoader().getResourceAsStream("configuration.properties");

+0

没错,没有理由在这里使用一个文件。当'configuration.properties'捆绑在一个war中时,你不能以File的形式访问它。它在你的IDE中工作的原因是因为你仍然可以作为一个文件来访问它。 https://issues.apache.org/jira/browse/SUREFIRE-855与此相关,它现在允许您使用artifact而不是classfolder进行测试,就像“在制作中”一样。 –

0

打开你的战争,并包含应用程序的JAR文件。确保您尝试打开的资源位于正在部署的jar中(在战争中)。大多数情况都发生在我身上,这是因为我没有告诉我的构建过程需要将该文件复制到部署中。类文件自动进入,但并不总是资源文件。

+0

我在质询时说,它是存在的,我可以看到它 –

相关问题