简体   繁体   English

如何通过提及关键字仅在第一次出现时替换特定行

[英]How to replace specific line only on 1st occurence by mentioning keyword

I have below pom.xml file.我有以下 pom.xml 文件。 I want to replace the version of the project which is in line 7. I will be able to provide <version> tag alone but not complete version details.我想替换第 7 行中的项目版本。我将能够单独提供<version>标记,但不能提供完整的版本详细信息。 Expecting a code which finds the 1st <version> tag line and replace that with <version>1.0.1</version>期望找到第一个<version>标记行并将其替换为<version>1.0.1</version>的代码

I started with the below java code but which is currently replacing the whole version tag in the entire pom.xml.我从下面的 java 代码开始,但目前正在替换整个 pom.xml 中的整个版本标记。

How do I replace 1st <version> tag line alone with <version>1.0.1</version>如何用<version>1.0.1</version>单独替换第一个<version>标记行

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.myspace</groupId>
  <artifactId>Test</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>kjar</packaging>
  <name>Test</name>
  <description></description>
  <dependencies>
    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-api</artifactId>
      <version>7.46.0.Final</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-internal</artifactId>
      <version>7.46.0.Final</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.optaplanner</groupId>
      <artifactId>optaplanner-core</artifactId>
      <version>7.46.0.Final</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.optaplanner</groupId>
      <artifactId>optaplanner-persistence-jaxb</artifactId>
      <version>7.46.0.Final</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.thoughtworks.xstream</groupId>
      <artifactId>xstream</artifactId>
      <version>1.4.11.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.kie</groupId>
        <artifactId>kie-maven-plugin</artifactId>
        <version>7.46.0.Final</version>
        <extensions>true</extensions>
      </plugin>
    </plugins>
  </build>
</project>

Java code Java 代码

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class OverwriteLine {
   public static void main(String args[]) throws IOException {
      //Instantiating the File class
      String cloneDirectoryPath = "D:\\project\\localrepo117";
      String filePath = cloneDirectoryPath+"\\pom.xml";
      //Instantiating the Scanner class to read the file
      Scanner sc = new Scanner(new File(filePath));
      //instantiating the StringBuffer class
      StringBuffer buffer = new StringBuffer();
      //Reading lines of the file and appending them to StringBuffer
      while (sc.hasNextLine()) {
         buffer.append(sc.nextLine()+System.lineSeparator());
      }
      String fileContents = buffer.toString();
      System.out.println("Contents of the file: "+fileContents);
      //closing the Scanner object
      sc.close();
      String oldLine = "<version>";
      String newLine = "<version>1.0.1</version>";
      //Replacing the old line with new line
      fileContents = fileContents.replaceAll(oldLine, newLine);
      //instantiating the FileWriter class
      FileWriter writer = new FileWriter(filePath);
      System.out.println("");
      System.out.println("new data: "+fileContents);
      writer.append(fileContents);
      writer.flush();
   }
}

I suggest that you read file "pom.xml", line by line.我建议您逐行阅读文件“pom.xml”。 If the line read is the line you want to change, then change it otherwise leave it as it is.如果读取的行是您要更改的行,则更改它,否则保持原样。 Then write the line that you read to a temporary file.然后将您读取的行写入临时文件。 Once you have read all the lines in file "pom.xml", delete it and rename the temporary file to "pom.xml".阅读完文件“pom.xml”中的所有行后,将其删除并将临时文件重命名为“pom.xml”。

The below code does this.下面的代码就是这样做的。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class OverwriteLine {

    public static void main(String[] args) {
        Path sourcePath = Path.of("pom.xml");
        Path targetPath = Path.of("tmp.xml");
        boolean error = false;
        try (BufferedReader br = Files.newBufferedReader(sourcePath);
             BufferedWriter bw = Files.newBufferedWriter(targetPath,
                                                         StandardOpenOption.CREATE,
                                                         StandardOpenOption.TRUNCATE_EXISTING,
                                                         StandardOpenOption.WRITE)) {
            boolean found = false;
            String line = br.readLine();
            while (line != null) {
                if (!found) {
                    if (line.trim().startsWith("<version>")) {
                        found = true;
                        line = line.replace("1.0.0", "1.0.1");
                    }
                }
                bw.write(line);
                bw.write(System.lineSeparator());
                line = br.readLine();
            }
        }
        catch (IOException xIo) {
            error = true;
            xIo.printStackTrace();
        }
        if (!error) {
            try {
                Files.delete(sourcePath);
                Files.move(targetPath, sourcePath);
            }
            catch (IOException xIo) {
                xIo.printStackTrace();
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM