Solved

Search/Find and Replace in Java

Posted on 2008-10-13
15
426 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Do you use a spreadsheet like Microsoft's Excel?  Have you ever wanted to link out to a non excel file on your computer or network drive?  This is the way I found to do it!
After seeing numerous questions for Dynamic Data Validation I notice that most have used Visual Basic to solve the problem. This suggestion is purely formula based and can be used in multiple rows.
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…
This Micro Tutorial will demonstrate on a Mac how to change the sort order for chart legend values and decrpyt the intimidating chart menu.

630 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