-2

Can someone explain me how to replace value in .txt file. For example I've got a 'Test.txt' file with a line:

 1,23343,EUR,1.45,${param1},Mr,${param2} 

and I've got a HashMap like this one below:

Map map= new HashMap(); map.put("param1", "1000"); map.put("param2", "4000"); 

So now I would like to use the key value of my HashMap and pass it to the .txt file but I have no idea how to do this.

My file Test.txt should look like

1,23343,EUR,1.45,1000,Mr,4000 

Please, help me. Thank you in advance.

5
  • Possible duplicate of Find and replace words/lines in a file Commented Jan 14, 2016 at 18:35
  • Your file need to be in memory as text and then you can apply a replaceAll on the text. A file is just bytes on a disk, you can't pass anything to it. Commented Jan 14, 2016 at 18:38
  • 1
    It is not clear what you mean by "pass it to the .txt file". Do you want to write to the file? Do you want to read a particular line from the file, that matches your key? Commented Jan 14, 2016 at 18:39
  • I think you're asking how to replace param1 with 1000 and param2 with 4000. What have you tried so far? Look into how to read, parse, and write lines in a text file. This is basic stuff. Commented Jan 14, 2016 at 18:41
  • this isn't javascript / jsp file you dont need ${param1} and you cannot pass it to a text file. you can just create a buffer reader. read from the file, and write values using basic String manipulation tricks Commented Jan 14, 2016 at 18:44

2 Answers 2

0

You could do this on the command line with the envsubst command.

export param1=1000 export param2=4000 envsubst < original.txt > new.txt 

envsubst is a standard command line utility in many linux distros.

Sign up to request clarification or add additional context in comments.

Comments

0

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/text/StrSubstitutor.html

Example:

 Map map = HashMap(); map.put("param1", "1000"); map.put("param2", "4000"); StrSubstitutor sub = new StrSubstitutor(map); String resolvedString = sub.replace("1,23343,EUR,1.45,${param1},Mr,${param2}"); 

yielding:

1,23343,EUR,1.45,1000,Mr,4000

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.