How to get regex to get the value after name = in a file, and replace it. I have a file called: 'myfile.txt'.
public static void main(String[] args)
File TextFile = new File("C:\\text.txt");
if (TextFile.exists()) {
try {
ReplaceWordInFile(TextFile, "haical", "arnanda");
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void ReplaceWordInFile(File MyFile, String OldText, String NewText)
throws IOException {
File tempFile = File.createTempFile("filetemp", ".tmp");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(MyFile);
BufferedReader br = new BufferedReader(fr);
while (br.ready()) {
fw.write(br.readLine().replaceAll(OldText, NewText) + "\n");
}
fw.close();
br.close();
fr.close();
tempFile.renameTo(MyFile);
}
Contents of the file C:\text.txt is:
name = haical
address = Michigan 48309, Amerika Serikat
age = 19
gender = male
activity = school
hoby = hiking, travel
If I run the program above in the first line, name = haical will change to name = arnanda.
My problem is that the value from name isn't 'haical' but another value, so I want to get the value after name = blablabla.
Furthermore, sometimes the statement name = haical won't keep it's number of spaces & changes its position.
Example of the contents of the output at a later time is:
address = Michigan 48309, Amerika Serikat
name = haical
age = 19
gender = male
activity = school
hoby = hiking, travel
So it's not always on the first line and some spaces after the = , but it will always be on line starting with name =.
Thanks in advance.