Gradle删除注释并重新格式化属性文件

问题描述 投票:1回答:1

当我尝试在Gradle中编辑属性时,它会重新格式化我的整个属性文件并删除注释。我假设这是因为Gradle正在读取和写入属性文件的方式。我想只更改一个属性并保持其余属性文件不变,包括保留当前注释和值的顺序。使用Gradle 5.2.1可以做到这一点吗?

我试图使用setProperty(不写入文件),使用了另一个编写器:(versionPropsFile.withWriter { versionProps.store(it, null) } )

并尝试了一种不同的方式来读取属性文件:versionProps.load(versionPropsFile.newDataInputStream())

这是我目前的Gradle代码:

   File versionPropsFile = file("default.properties");

   def versionProps = new Properties() 

   versionProps.load(versionPropsFile.newDataInputStream())

    int version_minor = versionProps.getProperty("VERSION_MINOR")
    int version_build = versionProps.getProperty("VERSION_BUILD")

    versionProps.setProperty("VERSION_MINOR", 1)
    versionProps.setProperty("VERSION_BUILD", 2)

    versionPropsFile.withWriter { versionProps.store(it, null) }

以下是gradle触摸它之前属性文件的一部分:

# Show splash screen at startup (yes* | no)
SHOW_SPLASH = yes

# Start in minimized mode (yes | no*)
START_MINIMIZED = no

# First day of week (mon | sun*)
# FIRST_DAY_OF_WEEK = sun

# Version number
# Format: MAJOR.MINOR.BUILD

VERSION_MAJOR = 1
VERSION_MINOR = 0
VERSION_BUILD = 0

# Build value is the date

BUILD = 4-3-2019

以下是Gradle的作用:

#Wed Apr 03 11:49:09 CDT 2019
DISABLE_L10N=no
LOOK_AND_FEEL=default
ON_MINIMIZE=normal
CHECK_IF_ALREADY_STARTED=YES
VERSION_BUILD=0
ASK_ON_EXIT=yes
SHOW_SPLASH=yes
VERSION_MAJOR=1
VERSION_MINOR=0
VERSION_BUILD=0
BUILD=04-03-2019
START_MINIMIZED=no
ON_CLOSE=minimize
PORT_NUMBER=19432
DISABLE_SYSTRAY=no
java gradle properties-file
1个回答
1
投票

这本身并不是Gradle问题。 Java的默认Properties对象不保留属性文件的任何布局/注释信息。例如,您可以使用Apache Commons Configuration来获取布局保留属性文件。

这是一个自包含的示例build.gradle文件,用于加载,更改和保存属性文件,保留注释和布局信息(至少达到示例文件所需的程度):

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.apache.commons:commons-configuration2:2.4'
    }
}

import org.apache.commons.configuration2.io.FileHandler
import org.apache.commons.configuration2.PropertiesConfiguration
import org.apache.commons.configuration2.PropertiesConfigurationLayout

task propUpdater {
    doLast {
        def versionPropsFile = file('default.properties')

        def config = new PropertiesConfiguration()
        def fileHandler = new FileHandler(config)
        fileHandler.file = versionPropsFile
        fileHandler.load()

        // TODO change the properties in whatever way you like; as an example,
        // we’re simply incrementing the major version here:
        config.setProperty('VERSION_MAJOR',
            (config.getProperty('VERSION_MAJOR') as Integer) + 1)

        fileHandler.save()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.