首页 > 解决方案 > Gradle 删除注释并重新格式化属性文件

问题描述

当我尝试在 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

标签: javagradleproperties-file

解决方案


这本身不是 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()
    }
}

推荐阅读