Solved

Search/Find and Replace in Java

Posted on 2008-10-13
15
420 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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Excel 6 19
+1 to an even value 4 15
TT Master Button 18 16
Conditional formatting based on date 2 12
Improved? Move/Copy Add-in Replacement - How to avoid the annoying, “A formula or sheet you want to move or copy contains the name XXX, which already exists on the destination worksheet.” David Miller (dlmille)  It was one of those days… I wa…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This Micro Tutorial demonstrates how to create Excel charts: column, area, line, bar, and scatter charts. Formatting tips are provided as well.
This Micro Tutorial demonstrate the bugs in Microsoft Excel for Mac with Pivot Charts.

760 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

21 Experts available now in Live!

Get 1:1 Help Now