Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Search/Find and Replace in Java

Posted on 2008-10-13
15
Medium Priority
?
429 Views
Last Modified: 2013-11-23
Here is my the scenario:
Lets say we have 2 files
1. XMl file
2. Excel file

Xml file has a text tage eg: <TEXT>Standard Report</TEXT>

Excel file has 2 columns
TEXT in English         Text IN French
Standard Report          Rapport type

code should read the excle column 'TEXT in English' and find the word in XML file, once found, replace it with excel column 'Text in French'and then move on to the next row of Excel file and process the same until the end of the file.
0
Comment
Question by:MEINKIYAKAROON
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 7
15 Comments
 
LVL 1

Expert Comment

by:timbonicus
ID: 22708157
Certainly the hard part about this problem is parsing the files, the actual search and replace is not too difficult. The example below assumes you have read the XML file into a String object with FileReader and parsed the Excel file into a HashMap of <String,String> (text to replace, replacement text).

I used String.replaceAll, but you could certainly do something more powerful with the java.util.regex package (Pattern and Matcher).
	String xmlFile = readXMLFile(myFile);
	HashMap<String,String> replace = readExcelFile(myExcel);
	
	Iterator<String> it = replace.keySet().iterator();
	while (it.hasNext()) {
		String key = it.next();
		xmlFile = xmlFile.replaceAll(key, replace.get(key));
	}
	System.out.println(xmlFile);

Open in new window

0
 
LVL 5

Expert Comment

by:muktajindal
ID: 22708481
You may modify the attached code snippet to parse an excel file. Then use the values map to replace the values as described above.

	/*
	 * Function to read values from CSV file and store them in a list 
	 */
	public static Map<String, String> readValuesfromCSV() {
		
		String fName = "..\\TestData\\TestData.csv";
		Map<String, String> map = new HashMap<String, String>();
		FileInputStream fis = null;
		
		try {
			fis = new FileInputStream(fName);
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
		}
 
		try {
			BufferedReader br =new BufferedReader(new InputStreamReader(fis));
			String thisLine=br.readLine();
 
			while ((thisLine=br.readLine())!= null) {
				String[] arr=thisLine.split(",");
				if (arr.length!=0) {
					try {
						String english = arr[0];
						String french = arr[1];
						map.put(english, french);
					} catch(Exception e) {
						System.out.println(e.getMessage());
						continue;
					}				 
				}	  
			}
		} catch(Exception e) {
			System.out.println(e.getMessage());
		}
 
		return map;
	}

Open in new window

0
 

Author Comment

by:MEINKIYAKAROON
ID: 22708562
I really apologise about java knowledge , could you please write me the steps from start to finish and how do I compile this code and test it.

Thanks for yor help
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 5

Expert Comment

by:muktajindal
ID: 22708677
You will need to open your excel file and save it as csv file. Accept all the Yes/No pop-ups while saving as csv. Use the attached java file to use this csv file to modify your xml file. (Remove .txt from all the filenames)
FileWriteSample.java.txt
excel.csv.txt
excel.xls.txt
xml.xml.txt
0
 
LVL 5

Expert Comment

by:muktajindal
ID: 22708680
Save csv and xml file in C: drive and then run this java file. You should see the modification done in the xml file as per your csv file entries.
0
 

Author Comment

by:MEINKIYAKAROON
ID: 22711153
how to run this java file (filewritesample.java), in which environment??
0
 

Author Comment

by:MEINKIYAKAROON
ID: 22711457
I have attached the error file while running the program.
thanks for your help


FileWriteSample.doc
0
 

Author Comment

by:MEINKIYAKAROON
ID: 22717573
Mukta, could you please answer as are close to the solution.
 
Thanks
0
 
LVL 5

Expert Comment

by:muktajindal
ID: 22717946
Seems to be some classpath issue.. try giving the classpath while executing the class from command line. If you are using any IDE like eclipse, try executing it from there.
0
 
LVL 5

Expert Comment

by:muktajindal
ID: 22717972
Are you sure that the java file compiled successfully ? Make sure that package (com.tests) is correct.
Try following command (assuming that FileWriteSample.class is paced in C:\Java) :

java -cp C:\Java com.tests.FileWriteSample

0
 

Author Comment

by:MEINKIYAKAROON
ID: 22721224
Please see the attached file.
Thanks for your help

Java-Code-error.doc
0
 
LVL 5

Expert Comment

by:muktajindal
ID: 22727807
Can you tell me the complete folder path where you have placed FileWriteSample.java ? I really doubt that it does not match the package defined in it.
0
 
LVL 5

Accepted Solution

by:
muktajindal earned 1000 total points
ID: 22727841
Your scenario is as follows :
- You have defined package as com.tests in FileWriteSample.java
- You have compiled FileWriteSample.java and got FileWriteSample.class
- Both these files are in C:\Java

You need to do the following :
- Create folder structure C:\Java\com\tests\
- Copy FileWriteSample.class to C:\Java\com\tests\
- Execute it using following command from C:\Java
java -cp C:\Java com.tests.FileWriteSample
0
 

Author Closing Comment

by:MEINKIYAKAROON
ID: 31406249
This is excellent, this code worked as exactly I needed. Very well done.

Thanks a lot :)
0
 

Author Comment

by:MEINKIYAKAROON
ID: 22740705
Please close this question
0

Featured Post

Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Access developers frequently have requirements to interact with Excel (import from or output to) in their applications.  You might be able to accomplish this with the TransferSpreadsheet and OutputTo methods, but in this series of articles I will di…
This article describes a serious pitfall that can happen when deleting shapes using VBA.
This Micro Tutorial will demonstrate how to use longer labels with horizontal bar charts instead of the vertical column chart.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Suggested Courses

704 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question