【问题标题】:Issue with file path in Java/LiferayJava/Liferay 中的文件路径问题
【发布时间】:2015-09-10 12:41:52
【问题描述】:

我尝试了多种方式从资源文件夹加载属性文件。

每次,我都会收到一个找不到文件的异常。我的代码如下:

 Properties prop = new Properties();
        FileInputStream inputStream = new FileInputStream("/resource/excelfilepath.properties");
        prop.load(inputStream);
        String path = prop.getProperty("excelPath");
        System.out.println("Excel File Path "+ path);

我的项目结构如下,

文件路径字面量所需的结构是什么?

【问题讨论】:

  • 这可能是完全错误的:你试过".//resource//excelfilepath.properties"吗?在这里查看异常的描述可能会有所帮助。另外,你提到的代码是在createUser.java 类中吗?
  • 我试过了,但是获取系统找不到指定的路径
  • 是的,代码在createUser.java文件中提到
  • 请使用Java Naming Conventions 在此处发帖 - 这将使其他人更容易理解您的代码。

标签: java liferay inputstream liferay-6 fileinputstream


【解决方案1】:

我不认为您真的想从网络资源中读取....properties 文件。这样,访问您服务器的所有用户都可以看到内容 - 只要您没有在 web.xml 中明确隐藏它。

更常见的做法是将其放入访问类旁边的类路径中。这样您就可以使用类加载器访问它,并且它不再对网络用户可见:

Properties prop = new Properties();
prop.load(CreateUser.class.getResourceAsStream("excelfilepath.properties"));

但是当您使用 Liferay 时,您也应该使用它的配置。只需将属性 UserCreationPortlet.excelPath 添加到您的 portal-ext.properties 并使用:

String path = PrefsPropsUtil.getString("UserCreationPortlet.excelPath", defaultPath);

【讨论】:

    【解决方案2】:

    你需要告诉服务器你的根文件夹在哪里:

    使用 Tomcat:在 catalina.properties 将属性 shared.loader 附加到您的。

    使用 Jboss :在您的 conf 文件夹中编辑 jboss-service.xml

    <classpath codebase="${jboss.home.url}/server/default/lib//proprietes/rootFolder" archives="*"/>
    

    我建议创建一个类来加载您的属性:

    喜欢:

    public static Properties charger(Class<?> pClass, String pFilename) {
    Properties aProperties = null;
    
    try {
        InputStream aIs = null;
        File aFile = new File(pFilename);
    
        if (!aFile.isAbsolute()) {
            aIs = pClass.getClassLoader().getResourceAsStream(pFilename);
            if (aIs == null) {
                return null;
            }
        } else if (!aFile.exists()) {
            return null;
        }
        if (aIs == null)
            aIs = new FileInputStream(aFile);
        InputStreamReader reader = new InputStreamReader(aIs, "UTF-8");
        aProperties = new Properties();
        aProperties.clear();
        aProperties.load(reader);
        reader.close();
        aIs.close();
    } catch (FileNotFoundException e) {
        LOG.error("Catch FileNotFoundException : ", e);
    } catch (IOException e) {
        LOG.error("Catch IOException : ", e);
    }
    return aProperties;
    }
    

    然后使用您希望的属性调用您的新类:

    protected static final Properties property  = ChargeurProprietes.charger( .class,"PATH");
    
    property.getProperty(NAME OF YOUR PROPERTY);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      相关资源
      最近更新 更多