Replacing text in files

Hi,

Can anyone help me to produce a new translated file which has the format as the original?

1) I'm looking to read in a file line by line.
2) For each word identified, parse to a method for translation. (some will not have a translation and will return as sent)
3) Write out to a new file with the same spacing with the translated text in place

I have so far:

 private void processChanges(TranslationProperties tp,
                                            String parsefilename,
                                            String outputpath,
                                            String filename) throws Exception {
              
         
             FileReader fr = new FileReader(parsefilename);
          LineNumberReader lr = new LineNumberReader(fr);
          StringBuffer sb = new StringBuffer();
          String str;

                               
          while ( (str = lr.readLine()) != null )
          {
                    StringTokenizer st = null;
                    String objClass = null;
                    String objName = null;
                     
            st = new StringTokenizer(str);
                                    
            String retrievedValue = tp.getValue(st);
      
            try
            {
                  System.out.println("writing to file:" +retrievedValue);
                  BufferedWriter out = new BufferedWriter(new                     (outputpath+filename, false));
                   
                   out.write(retrievedValue);
                   out.newLine();
                   out.close();
                            
              } catch (Exception e)
              {
                    logger.error("Error printing:" +retrievedValue+ " " +e);
                    errorCount++;
              }
                                    
              }
              lr.close();
                     
         }

Thanks
codemonkey156Asked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
Just keep a Map of replacements and then iterate the Map entries:

while(iter.hasNext()) {
    Entry e = (Entry)iter.next();
    String find = (String)e.getKey();
    String replace = (String)e.getValue();
}
line = line.replaceAll(find, replace);
// Now write the line to the new file
0
 
Mayank SAssociate Director - Product EngineeringCommented:
What is the problem that you are facing?

>> new BufferedWriter(new                     (

Is probably new BufferedWriter ( new FileWriter (

?

BTW, if you want to append, the second parameter has to be true instead of false.
0
 
CEHJCommented:
You can use the following:

http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html

If you put the code i posted earlier into a method call 'process' then you're more or less done
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
arun_kuttzCommented:
You could use java.io.StreamTokenizer.. Herez just a sample code that parses a text file for word tokens...
    .......
    .......
        try {
            // Create the tokenizer to read from a file
            FileReader rd = new FileReader("c:\\temp\\test.txt");
            StreamTokenizer st = new StreamTokenizer(rd);

            st.eolIsSignificant(true);

            // Parse the file
            int token = -1;
            do {
                token = st.nextToken();
                String word = null;
                if (token == StreamTokenizer.TT_WORD) {
                    word = st.sval;
                    out.write(parse(word));          <--------- call your parse funtion passing the word
                    out.write(' ');
                } else  {
                    out.write((char)token);
                }

            } while (token != StreamTokenizer.TT_EOF);
            rd.close();
        } catch (Exception e) {
        }
 .............

-KuTtZ
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Assuming that your String retrievedValue = tp.getValue(st); does most of the functionality (in the getValue () method), what are the problems you are facing as of now?
0
 
codemonkey156Author Commented:
Hi, I have been able to tokenize a line, translate and print. The problem is that I'm not spacing the tokens to the new file in the way that they are on the existing file. I have altered my code to use BufferedReader to take the whole line but I need to translate only the text and write out to the new file in the same spacing. I'm now getting syntax errors.

'iter' and 'line' are currently indicating syntax errors as I'm not sure what to define.


               private void processChanges(TranslationProperties tp,
                                                                             String parsefilename,
                                                                             String outputpath,
                                                                             String filename) throws Exception {
              

                try {
                    BufferedReader in = new BufferedReader(new FileReader(parsefilename));
                    String str;

                    while ((str = in.readLine()) != null) {

 
                                       process(tp, parsefilename, outputpath, filename, str);

                            String retrievedValue = tp.getValue(str);
      
                         System.out.println("retrievedValue:" +retrievedValue);
                     
                         writeFile(filename, outputpath, retrievedValue);
                     
                    }               
             
                              in.close();
          } catch (IOException e)
                    {
                          logger.error("Error writing:" +outputText+ " " +e);
                          errorCount++;

                     
         }
       }


  private void process(TranslationProperties tp, String parsefilename, String outputpath, String filename, String str) {
                    
              while(iter.hasNext()) {
                    
                  Entry e = (Entry)iter.next();
                  String find = (String)e.getKey();
                  String replace = (String)e.getValue();
              }
              line = line.replaceAll(find, replace);
        }

             
 private void writeFile(String f, String outputpath, String outputText) throws Exception {
                    
                       try
                    {
                                 BufferedWriter out = new BufferedWriter(new FileWriter(outputpath+f, true));
                         out.write(outputText);
                         out.newLine();
                         out.close();
                            
                    } catch (IOException e)
                    {
                          logger.error("Error writing:" +outputText+ " " +e);
                          errorCount++;
                    }
      
               }


0
 
CEHJCommented:
>>while(iter.hasNext()) {

You need to call

Iterator iter = yourCollection.iterator();

on the variable 'yourCollection' which should be a reference to the Map containing your find/replace Strings
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> line = line.replaceAll(find, replace);

'line' here is undefined. Is this supposed to be 'str' instead? And does it have to be inside the loop or outside? It anyway does not seem to be adding any functionality as the method returns nothing.
0
 
CEHJCommented:
>>line = line.replaceAll(find, replace);

You then need to write 'line' out to a new file
0
 
codemonkey156Author Commented:
I've resolved the syntax errors but still unfortunately not getting what I need out:

Feed in line:
TextA TextB TextC                TextD      TextE
Text1    Text2         Text3

reference file states:
TextD=TextZ
Text2=Text9

output file has:
TextZ
Text9

However, output file should have:
TextA TextB TextC                TextZ     TextE
Text1    Text9         Text3

Code snip below:

               private void processChanges(TranslationProperties tp,
                                                                             String parsefilename,  
                                                                             String outputpath,
                                                                              String filename) throws Exception {
         
                try {
                    BufferedReader in = new BufferedReader(new FileReader(parsefilename));
                    String str;

                    while ((str = in.readLine()) != null) {
 
                          str = process(tp, parsefilename, outputpath, filename, str);

                          String retrievedValue = tp.getValue(str);
      
                          System.out.println("retrievedValue:" +retrievedValue);
                     
                          writeFile(filename, outputpath, retrievedValue)      
                    }               
              in.close();
          } catch (IOException e) {
                     
         }
       }

              private String process(TranslationProperties tp,
                                                                  String parsefilename,
                                                                  String outputpath,
                                                                  String filename,
                                                                   String str) {
                    
                             StringTokenizer st = new StringTokenizer(str);
              String[] inText = new String[10];
              int i = 0;
          
              
              while (st.hasMoreTokens() & st != null) {
                    
                    i++;
                    inText[i] = st.nextToken();                           
                      System.out.println("inText: " +i+ " " +inText[i]);                
                  
                      String retrievedValue = tp.getValue("HpsRule",inText[i]);
                    System.out.println("retrievedValue:" +retrievedValue);
              
              }
            String translatedText = inText[i];
            return translatedText;
}


               private void writeFile(String f, String outputpath, String outputText) throws Exception {
                                        
              try
              {
                        BufferedWriter out = new BufferedWriter(new FileWriter(outputpath+f, true));
                          out.write(outputText);
                          out.newLine();
                          out.close();
                            
              } catch (IOException e)
              {
                    logger.error("Error writing:" +outputText+ " " +e);
                    errorCount++;
              }
      
}
0
 
CEHJCommented:
You don't need to tokenize the file - just keep a Map of replacements. You could put those in a Properties file


find1=replace1
find2=replace2



etc
0
 
codemonkey156Author Commented:
Thanks for the help. Solution found
0
 
CEHJCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.