如何使用java替换文件中特定行之后的字符串
我有类似的情况,如果找不到相似的字符串,我需要在批处理文件中更改一行。
假设我在批处理中有类似下面的代码(我知道它不是正确的代码,因为它只是一个虚拟的)
public static void main(String[] args) { if (user == '1234') { ENV DEV set DB myDBDEV set Excel myExecelDEV set API MyAPIURLDEV } elseif (user == '5678') { ENV UAT set DB myDBUAT set Excel myExecelUAT set API MyAPIURLUAT } } }
现在我希望java读取上面的文件,找到ENV作为DEV并更改值如myDBDEV,myExecelDEV,MyAPIURLDEV等。
我可以使用下面的代码找到行号
FileInputStream fis = new FileInputStream("C:\\Users\\owner\\Desktop\\batch\\MYbatch-env.csh"); InputStreamReader input = new InputStreamReader(fis); BufferedReader br = new BufferedReader(input); String data; String result = new String(); int i=0; while ((data = br.readLine()) != null) { i++; if(data.contains("ENV DEV")) { System.out.println("line number -> "+i); } result = result.concat(data + "\n"); }
我试过下面的代码,但那不是返回行号,所以我使用上面的方法
使用java查找文本文件中单词的行号
我也试过下面的方法,但它似乎不起作用
如何使用java替换文件中特定行之后的字符串
现在问题语句是replaceAll函数将删除所有键但我想删除下一个键的键意味着值。 它是一个文本作为字符串而不是一个hashmap类的东西,
如果是块,如果DB字符串是myDBDEV2,那么我想将值更改为myDBDEV
例:
如果发现低于字符串
ENV DEV
然后低于值应该检查关键数据库的值,如果没有找到所需的值则替换
set DB myDBDEV set Excel myExecelDEV set API MyAPIURLDEV
主要的是代码应该只在块中进行更改,否则如果变量应该作为我在上面的URL中显示的文件示例受到影响。
以下解决方案适合我
public static void main(String[] args) throws Exception { String filepath= "C:\\Users\\Demo\\Desktop\\batch\\Demo.sh"; FileInputStream fis = new FileInputStream(filepath); InputStreamReader input = new InputStreamReader(fis); BufferedReader br = new BufferedReader(input); String data; String result = new String(); int lineNumber=0; int i=0; while ((data = br.readLine()) != null) { i++; if(data.contains("My String data")) { System.out.println("line number -> "+i); lineNumber=i; break; } result = result.concat(data + "\n"); } br.close(); lineNumber=lineNumber+1; System.out.println(lineNumber); String Mystring =" Mystring"; String Mystringline = Files.readAllLines(Paths.get(filepath)).get(lineNumber-1); // get method count from 0 so -1 System.out.println("Line data ->> "+Mystringline); if(!Mystringline.equalsIgnoreCase(Mystring)) { setVariable(lineNumber, Mystring, filepath); }else { System.out.println("Mystring is already pointing to correct DB"); } System.out.println("Succesfully Change"); } public static void setVariable(int lineNumber, String data, String filepath) throws IOException { Path path = Paths.get(filepath); List lines = Files.readAllLines(path, StandardCharsets.UTF_8); lines.set(lineNumber - 1, data); Files.write(path, lines, StandardCharsets.UTF_8); } }