【问题标题】:How to escape backslashes in a filtered properties files with Maven?如何使用 Maven 在过滤的属性文件中转义反斜杠?
【发布时间】:2017-04-11 13:31:42
【问题描述】:

我的 pom.xml 文件如下所示:

<testResource>
    <directory>src/test/resources</directory>
    <filtering>true</filtering>
    <includes>
        <include>env.properties</include>
    </includes>
</testResource>

我的 env.properties 看起来像这样:

my.path=${project.build.directory}

当我构建项目时,env.properties 生成如下:

my.path=C:\\path\\to\\directory

我怎样才能得到下面的结果?

my.path=C:\\\\path\\\\to\\\\directory

【问题讨论】:

  • 为什么要这个输出? C:\\\\path\\\\to\\\\directory 是属性文件中的错误路径。
  • @Tunaki 好吧,我正在使用一个第三方库,它会乱用像 C:pathtodirectory 这样的文件名。我的实际解决方法是在将文件名(filename.replace("\\", "/"))传递给库之前手动转义它们。我希望找到一个纯 Maven 解决方案。
  • @Tunaki 你回复得比我更正。

标签: java maven escaping backslash maven-resources-plugin


【解决方案1】:

这是一件奇怪的事情,但您可以使用build-helper-maven-plugin:regex-property 目标。这个目标可以创建一个 Maven 属性,该属性是对某个值应用正则表达式的结果,可能需要替换。

在这种情况下,正则表达式将替换所有黑斜杠,即\\,因为它们需要在正则表达式中进行转义,替换为 4 个反斜杠。请注意,该插件会自动转义 Java 的正则表达式,因此您不需要也对其进行 Java 转义。

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <version>1.12</version>
  <executions>
    <execution>
      <id>escape-baskslashes</id>
      <phase>validate</phase>
      <goals>
        <goal>regex-property</goal>
      </goals>
      <configuration>
        <value>${project.build.directory}</value>
        <regex>\\</regex>
        <replacement>\\\\\\\\</replacement>
        <name>escapedBuildDirectory</name>
        <failIfNoMatch>false</failIfNoMatch>
      </configuration>
    </execution>
  </executions>
</plugin>

这会将所需的路径存储在 escapedBuildDirectory 属性中,您以后可以在资源文件中将其用作标准 Maven 属性,例如 ${escapedBuildDirectory}。该属性是在 validate 阶段创建的,这是 Maven 在构建过程中调用的第一个阶段,因此它也可以在其他任何地方用作插件参数。

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 2015-03-29
    • 1970-01-01
    相关资源
    最近更新 更多