Solved

Search/Find and Replace in Java

Posted on 2008-10-13
15
421 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
  • 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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 250 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
The view will learn how to download and install SIMTOOLS and FORMLIST into Excel, how to use SIMTOOLS to generate a Monte Carlo simulation of 30 sales calls, and how to calculate the conditional probability based on the results of the Monte Carlo …
This Micro Tutorial will demonstrate the scrolling table in Microsoft Excel using the INDEX function.

947 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now