[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Replacing text in files

Posted on 2006-05-05
13
Medium Priority
?
179 Views
Last Modified: 2010-03-31
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
0
Comment
Question by:codemonkey156
  • 6
  • 3
  • 3
  • +1
13 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 750 total points
ID: 16615598
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
 
LVL 30

Expert Comment

by:Mayank S
ID: 16615675
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 16615834
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
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.

 
LVL 3

Expert Comment

by:arun_kuttz
ID: 16617315
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
 
LVL 30

Expert Comment

by:Mayank S
ID: 16621985
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
 

Author Comment

by:codemonkey156
ID: 16631700
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 16632039
>>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
 
LVL 30

Expert Comment

by:Mayank S
ID: 16636493
>> 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
 
LVL 86

Expert Comment

by:CEHJ
ID: 16636975
>>line = line.replaceAll(find, replace);

You then need to write 'line' out to a new file
0
 

Author Comment

by:codemonkey156
ID: 16637775
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 16637890
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
 

Author Comment

by:codemonkey156
ID: 16665282
Thanks for the help. Solution found
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16665666
:-)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month20 days, 4 hours left to enroll

873 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