Replace string in ms word file

Salue,
I need to add a functionality to my Java app by allowing the replacement of strings in ms word files.
Basically I need to use an original MS Word file as template and then populate it with data,
replacing some keywords. And I need to do this with Java.
I know MS Word is binary and not text file, so I was wondering if there is any Java API to let me do this?
Merci, Irene

Irene,
It is possible to use ms word(.doc) or openoffice(.odt) templates and populate them with data.
I came across this solution while trying to convert to pdf, but it is usefull in replacing also.
import officetools.OfficeFile; // officetools.jar from this website http://www.dancrintea.ro/doc-to-pdf/
FileInputStream fis = new FileInputStream(new File("your_template.doc"));
FileOutputStream fos = new FileOutputStream(new File("your_final_result.doc"));
OfficeFile f = new OfficeFile(fis,"localhost","8100", true);
*f.replaceAll("hello","salue :) ");*
f.write(fos);

Similar Messages

  • Reading text file, Replace string, Write to new file....

    I'm kind a lost of on this problem. Using the BufferedReader class and BufferedWriter class, develop an application that reads lines of text from a file. Replace any occurrence of the word *?the?* with *?JAVAJAVA?* and change all characters to upper case before writing each line to a different text file named outfile.txt. Finally, have your application use the appropriate method on the File class to return the absolute path of the outfile.txt file and output the path to the screen.
    * Created December 10, 2008
    * @author Fausto Rivera
    * Colorado Technical University - Online Campus
    * IT271-0804B-02 Intermediate Object Oriented Programming II
    * Phase 2 IP
    * Instructor: Cheryl B Frederick
    import java.io.File;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    public class FRiveraReader {
          public static void main(String[] args) {
          // instantiated a new application object to initialize the application
          FRiveraReader application = new FRiveraReader();}
    //      application.getReadfr();  // call to openFile method
    //      application.doWritefr(); // call to readRecords method
    //      application.closeFile();  // call to closeFile method
    public FRiveraReader(){}
      public void getReadfr (String friveraInfile, String fr []){
       int i;
       File fileName = makeAbsoluteFilename(friveraInfile);
       try{
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        String line = reader.readLine();
         i=0;
          while (line != null) {
           fr[i] =line;
           line = reader.readLine();
        i++;
      reader.close();
    catch(IOException e) {
    System.out.println("Error with reading file:" + friveraInfile);
    }//end of getOrder method
    public void doWritefr(String friveraOutfile, String fw[]){//String name of file, String array to be written
    int i;
    File fileNameout = makeAbsoluteFilename(friveraOutfile);
    try {
    BufferedWriter writer = new BufferedWriter(new FileWriter (fileNameout));
      i=0;
      while (fw[i] != null) {
       writer.write(fw[i] + "%n"); //need delimiters between data in file;also, reader reads a line
       i++;
      writer.close();
    catch(FileNotFoundException e) {
    System.out.println("File not found");
    catch(IOException e) {
    System.out.println("Error with reading file:" + friveraOutfile);
    }//end of getOrder method
    private File makeAbsoluteFilename(String friveraOutfile)//these 2 classes used to resolve file name
            File file = new File(friveraOutfile);
            if(!file.isAbsolute()) {
                file = new File(friveraOutfile);
            return file;

    I have modified my code as far as being able to create a text file, write to string, and change to upper case. Now, how can I connected input to the output stream and then replace all the instances of the string "the" for the string "JAVAJAVA"? When the file is created, it goes into a loop writing the following:
    nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%
    Here is my modified code
    import java.io.File;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    public class FRiveraReader {
    public FRiveraReader() {}
    private static final String inFile = "C:\\Documents and Settings\\Fausto Rivera\\My Documents\\NetBeansProjects\\Rivera_F_IT271_0804B_02_PH2_IP\\friverainfile.txt";//the path name of your file
      public void myReadfr (){
       try {
        BufferedReader reader = new BufferedReader(new FileReader(inFile));
        //String "JAVAJAVA" = String "the";
        System.out.println(inFile);
        String line = reader.readLine();
          while (reader != null) {
           line = reader.readLine();
      reader.close();
    catch(IOException e) {
    System.out.println("Error with reading file:" + inFile);
    }//end of myReadfr method
    public void myWritefr(){//String name of file, String array to be written
    File outFile = new File ("C:\\Documents and Settings\\Fausto Rivera\\My Documents\\NetBeansProjects\\Rivera_F_IT271_0804B_02_PH2_IP\\myoutFile.txt");
    try {
    BufferedWriter writer = new BufferedWriter(new FileWriter (outFile));
    String newline = writer.toString() .toUpperCase();
      while (writer != null) {
       writer.write(newline + "%n"); //need delimiters between data in file;also, reader reads a line
      writer.close();
    catch(FileNotFoundException e) {
    System.out.println("File not found");
    catch(IOException e) {
    System.out.println("Error writing file:" + outFile);
    }//end of getOrder method
    private File makeAbsoluteFilename(String myoutFile)//these 2 classes used to resolve file name
            File file = new File(myoutFile);
            if(!file.isAbsolute()) {
                file = new File(myoutFile);
            return file;
      }Edited by: FRiveraJr on Dec 17, 2008 12:10 PM

  • Flash Charts - How to manipulate the #data# replacement string in XML

    I have a problem with the XML file for a flash chart. I am trying to display a 2dColumn chart of an SQL query with the general form:
    select null link, x as name, sum(y) as value from z group by (x);
    this generates multiple rows, which are displayed as a bar in the chart. So far so good. The problem is, that each row is defined as a block in the chart, but only one name entry is created "value", which is displayed in the legend of the chart.
    I can display the block names on the x-axis of the chart, however, I can't rotate them, so that they don't overlap in the display, which I would be able to do with names. I assume, that the blocks are defined in the #data# replacement string of the XML file. I would like to change the generated XML replacement string from the SQL to make each row selected a different name, and only have one block ("value").
    What would be the easiest way to achieve this?

    user587996,
    There's no way to manipulate the #data# replacement directly, but you could generate your own XML (see Re: Apex changing nulls to zeroes when creating Flash Charts for one way to do it).
    When you say "I can't rotate them, so that they don't overlap in the display" -- have you tried the Labels Rotation chart attribute, or is that not working?
    - Marco

  • Editing TEXT in WORD file.

    Hi,
    Is it possible to EDIT a text file (word) from FORMS 10g. Let's say I want to FIND and REPLACE text in a word file. Is there any tools or JAVA code that can help me achieve this?
    Thanks in advance,
    Marc.

    The Adobe Reader for SymbianOS isn't a PDF editor. You'd need Acrobat
    for that, using the Text Touch-up Tool.
    Aandi Inston

  • Search and replace strings in a file while ignoring substrings

    Hi:
    I have a java program that searches and replaces strings in a file. It makes a new copy of the file, searches for a string in the copy, replaces the string and renames the new copy to the original file, thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but searching for "Topabcd" and replacing it doesnot work because there is a match for "abcd" in a different search scenario. How can I modify the code such that if "abcd" is already searched and replaced then it should not be searched for again or rather search for "abcd" as entire string and not if its a substring of another string.
    In the below code output, all instances of "abcd" and the ones of "Topabcd" are replaced by ABCDEFG and TopABCDEF respectively, whereas according to the desired output, "abcd" should be replaced by ABCDEFG and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
              String find_productstring = "abcd";
              String replacement_productstring = "ABCDEFG";
              compsXml = new FileReader(compsLoc);
              compsConfigFile = new BufferedReader(compsXml);
              File compsFile =new File("file.xml");
              File compsNewFile =new File("file1.xml");
              BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
              while ((compsLine = compsConfigFile.readLine()) != null)
                    new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
                    out.write(new_compsLine);
                    out.write("\n");
                out.close();
                compsConfigFile.close();
                compsFile.delete();
                compsNewFile.renameTo(compsFile);
            catch (IOException e)
            //since "Topabcd" contains "abcd", which is the search above and hence the string "Topabcd" is not replaced correctly
             try
                   String find_producttopstring = "Topabcd";
                   String replacement_producttopstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
                   compsConfigFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
                   BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
                   while ((compsLine = compsConfigFile.readLine()) != null)
                         new_compsLine =compsLine.replaceFirst(find_producttopstring, replacement_producttopstring);
                         out.write(new_compsLine);
                         out.write("\n");
                     out.close();
                     compsConfigFile.close();
                     compsFile.delete();
                     compsNewFile.renameTo(compsFile);
                 catch (IOException e)
            }Thanks a lot!

    Hi:
    I have a java program that searches and replaces
    strings in a file. It makes a new copy of the file,
    searches for a string in the copy, replaces the
    string and renames the new copy to the original file,
    thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but
    searching for "Topabcd" and replacing it doesnot work
    because there is a match for "abcd" in a different
    search scenario. How can I modify the code such that
    if "abcd" is already searched and replaced then it
    should not be searched for again or rather search for
    "abcd" as entire string and not if its a substring of
    another string.
    In the below code output, all instances of "abcd" and
    the ones of "Topabcd" are replaced by ABCDEFG and
    TopABCDEF respectively, whereas according to the
    desired output, "abcd" should be replaced by ABCDEFG
    and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
    String find_productstring = "abcd";
    String replacement_productstring = "ABCDEFG";
    compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    BufferedReader(compsXml);
    File compsFile =new File("file.xml");
    File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    FileWriter("file1.xml"));
    while ((compsLine =
    compsConfigFile.readLine()) != null)
    new_compsLine
    =compsLine.replaceFirst(find_productstring,
    replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
    catch (IOException e)
    //since "Topabcd" contains "abcd", which is
    the search above and hence the string "Topabcd" is
    not replaced correctly
    try
                   String find_producttopstring = "Topabcd";
    String replacement_producttopstring =
    topstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    gFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    dWriter(new FileWriter("file1.xml"));
    while ((compsLine =
    compsLine = compsConfigFile.readLine()) != null)
    new_compsLine
    new_compsLine
    =compsLine.replaceFirst(find_producttopstring,
    replacement_producttopstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
                 catch (IOException e)
    Thanks a lot!I tried the matches(...) method but it doesnt seem to work.
    while ((compsLine = compsConfigFile.readLine()) != null)
    if(compsLine.matches(find_productstring))
         System.out.println("Exact match is found for abcd");
         new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
         else
         System.out.println("Exact match is not found for abcd");
         out.write(compsLine);
         out.write("\n");

  • Tell me Logic for search for duplicate words(or strings) in a large file.

    Search for duplicate words (or strings) in a text file containing one word per line. For each word that occurs more than once in the flat file output should be as follows
    <word> <number of occurrences> <line numbers in the file where the word occurs>
    For example, if the word Hello occurs thrice in a file at lines 100, 178 and 3456 the output should read
    Hello, 3, [100, 178, 3456]

    Incidentally i wrote similar code some days back. You need to do some modifications to get the exact output you want, but i hope it will be of some help.
    One more thing its written using JAVA5
    public class Test
         private static final String COLLECTIONS_TEXT = "C:\\Documents and Settings\\amrainder\\Desktop\\Collections.txt";
         public static void main(String[] args) throws IOException
              findDuplicateWords();
         private static void findDuplicateWords() throws IOException
              Collection<String> words = new LinkedHashSet<String>();
              File file = new File(COLLECTIONS_TEXT);
              StreamTokenizer streamTokenizer = new StreamTokenizer(new FileReader(file));
              int token = streamTokenizer.nextToken();
              while(token != StreamTokenizer.TT_EOF)
                   if(token == StreamTokenizer.TT_WORD)
                        words.add(streamTokenizer.sval);
                   token = streamTokenizer.nextToken();
              System.out.println(words);
    }Cheers,
    Amrainder

  • Replace string in a file

    I want a java program can replace string in a file with given string.
    for example,
    my file is
    abc 100
    aaa 110
    ded 123
    replace aaa with mmm.
    my codes is reading line by line and looking for aaa ,if read_line.index("aaa")> -1,then write mmm and aaa.substring
    Do you have ant other solutions?is there any file class method I can use?
    cheers.

    String content = <get file content>;
    String newContent = content.replaceAll( "aaa", "I get my homework on java.sun.com" );
    if( !newContent.equals(content) )
       <rewrite file contents>

  • I wrote an 2500 words assignment and saved in Microsoft word 97-2003 and by mistake replaced with another word file.How can i retain my original work?

    I wrote an 2500 words assignment and saved in Microsoft word 97-2003 and by mistake replaced with another word file.How can i retain my original work? 

    Hi,
    Does this happen to all 97-2003 Word files?
    Word 2013 now has lots of updates compared with earlier version of Word, lots of features have been updated. Use Word 2013 to open documents created in earlier versions of Word (Word 97-2003 format), you will probably encounter unexpected problems,
    expecially for those heavily formatted files.
    We would suggest you to convert your document to the Word 2013 file format, then you will be able to access the new and enhanced features in Word 2013.
    Regards,
    Ethan Hua
    TechNet Community Support
    It's recommended to download and install
    Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
    programs.

  • How do i restore a microsoft word file i replaced

    how do i restore a microsoft word file i replaced

    Did you save over the 'old' file - and now you want to recover it? AFAIK, it can't be done - that's what "Save as..." is for.
    Clinton

  • Open word file, stored in database through Forms.

    Assalam-o-Alikum
    to Genius of Oracle's
    I have stored the Word file name "MY_FILE.DOC" in oracle database. Now i want to open the file through Forms, remember i am using forms 6i. is there any body who help me to open the file.
    Best Regards
    Farrukh Shaikh

    Assalam-o-Alikum
    My in tension was not to hurt any body. if it did then sorry for that.
    here is the code through which i stored the file in database
    first create the DIRECTORY CREATE DIRECTORY generic AS 'C:\temp';---- --directory path where your files will be searched for storing.
    THEN
    create table my_blob_table
    pk_name varchar2(20) primary key,
    pk_value varchar2(20),
    col_document blob
    INSERT INTO MY_BLOB_TABLE
    (PK_NAME,PK_VALUE)
    ('A','A');
    COMMIT;
    CREATE OR REPLACE PROCEDURE load_blob_from_file
    ( src_file_name IN VARCHAR2
    , table_name IN VARCHAR2
    , column_name IN VARCHAR2
    , primary_key_name IN VARCHAR2
    , primary_key_value IN VARCHAR2 ) IS
    -- Define local variables for DBMS_LOB.LOADBLOBFROMFILE procedure.
    des_blob BLOB;
    src_blob BFILE := BFILENAME('GENERIC',src_file_name);
    des_offset NUMBER := 1;
    src_offset NUMBER := 1;
    -- Define a pre-reading size.
    src_blob_size NUMBER;
    -- Define local variable for Native Dynamic SQL.
    stmt VARCHAR2(2000);
    BEGIN
    -- Opening source file is a mandatory operation.
    IF dbms_lob.fileexists(src_blob) = 1 AND NOT dbms_lob.isopen(src_blob) = 1 THEN
    src_blob_size := dbms_lob.getlength(src_blob);
    dbms_lob.open(src_blob,DBMS_LOB.LOB_READONLY);
    278 Oracle Database 11g PL/SQL Programming
    END IF;
    -- Assign dynamic string to statement.
    stmt := 'UPDATE '||table_name||' '
    || 'SET '||column_name||' = empty_blob() '
    || 'WHERE '||primary_key_name||' = '||''''||primary_key_value||''' '
    || 'RETURNING '||column_name||' INTO :locator';
    -- Run dynamic statement.
    EXECUTE IMMEDIATE stmt USING OUT des_blob;
    -- Read and write file to BLOB.
    dbms_lob.loadblobfromfile( dest_lob => des_blob
    , src_bfile => src_blob
    , amount => dbms_lob.getlength(src_blob)
    , dest_offset => des_offset
    , src_offset => src_offset );
    -- Close open source file.
    dbms_lob.close(src_blob);
    -- Commit write.
    IF src_blob_size = dbms_lob.getlength(des_blob) THEN
    $IF $$DEBUG = 1 $THEN
    dbms_output.put_line('Success!');
    $END
    COMMIT;
    ELSE
    $IF $$DEBUG = 1 $THEN
    dbms_output.put_line('Failure.');
    $END
    RAISE dbms_lob.operation_failed;
    END IF;
    END load_blob_from_file;
    after create the PROCEDURE run the procedure
    begin
    load_blob_from_file('FILE_NAME.DOC',' my_blob_table','col_document','PK_NAME','A');
    end;

  • Convert SmartForm to Word File or EXCEL,POSSIBLE?

    Hi,
    I have a requirement to convert a SmartForm to Word File or EXCEL because they need to do some changes in the form.I know how to convert it to PDF but I don't know how to convert it to WORD or EXCEL.I've searched the forum and know i have to use the FM:CONVERT_ITF_TO_RTF.I'm a newbie and can anyone tell me how to use this FM or give me a example.Will it loose all the formatting?Thanks.

    CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
          EXPORTING
            formname = w_formname
          IMPORTING
            fm_name  = w_fmname.
        CALL FUNCTION w_fmname
          EXPORTING
            control_parameters = cparam
            output_options     = outop
            user_settings      = space
         IMPORTING
            job_output_info    =  tab_otf_data
         TABLES
            IT_VBRP = IT_VBAP[].
       if  sy-subrc IS INITIAL.
        ENDIF.
         tab_otf_final[] = tab_otf_data-otfdata[] .
    *--Start of PDF--
        CALL FUNCTION 'CONVERT_OTF'
         EXPORTING
           FORMAT                      = 'DOC''
           MAX_LINEWIDTH               = 255
      ARCHIVE_INDEX               = ' '
      COPYNUMBER                  = 0
      ASCII_BIDI_VIS2LOG          = ' '
      PDF_DELETE_OTFTAB           = ' '
         IMPORTING
           BIN_FILESIZE                = BIN_FILESIZE
      BIN_FILE                    =
          TABLES
            OTF                         = tab_otf_final
            LINES                       =  doc_tab
         EXCEPTIONS
           ERR_MAX_LINEWIDTH           = 1
           ERR_FORMAT                  = 2
           ERR_CONV_NOT_POSSIBLE       = 3
           ERR_BAD_OTF                 = 4
           OTHERS                      = 5
        IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
        ENDIF.
        DATA : FNAME TYPE STRING .
       FNAME = PATH.
       concatenate FNAME  VBELN  '.doc' into FNAME .
        CALL FUNCTION 'GUI_DOWNLOAD'
          EXPORTING
            BIN_FILESIZE                    = bin_filesize
            FILENAME                        = fname
           FILETYPE                        = 'BIN'
      APPEND                          = ' '
      WRITE_FIELD_SEPARATOR           = ' '
      HEADER                          = '00'
      TRUNC_TRAILING_BLANKS           = ' '
      WRITE_LF                        = 'X'
      COL_SELECT                      = ' '
      COL_SELECT_MASK                 = ' '
      DAT_MODE                        = ' '
      CONFIRM_OVERWRITE               = ' '
      NO_AUTH_CHECK                   = ' '
      CODEPAGE                        = ' '
      IGNORE_CERR                     = ABAP_TRUE
      REPLACEMENT                     = '#'
      WRITE_BOM                       = ' '
      TRUNC_TRAILING_BLANKS_EOL       = 'X'
      WK1_N_FORMAT                    = ' '
      WK1_N_SIZE                      = ' '
      WK1_T_FORMAT                    = ' '
      WK1_T_SIZE                      = ' '
         IMPORTING
           FILELENGTH                      = file_size
          TABLES
            DATA_TAB                        = doc_tab
      FIELDNAMES                      =
         EXCEPTIONS
           FILE_WRITE_ERROR                = 1
           NO_BATCH                        = 2
           GUI_REFUSE_FILETRANSFER         = 3
           INVALID_TYPE                    = 4
           NO_AUTHORITY                    = 5
           UNKNOWN_ERROR                   = 6
           HEADER_NOT_ALLOWED              = 7
           SEPARATOR_NOT_ALLOWED           = 8
           FILESIZE_NOT_ALLOWED            = 9
           HEADER_TOO_LONG                 = 10
           DP_ERROR_CREATE                 = 11
           DP_ERROR_SEND                   = 12
           DP_ERROR_WRITE                  = 13
           UNKNOWN_DP_ERROR                = 14
           ACCESS_DENIED                   = 15
           DP_OUT_OF_MEMORY                = 16
           DISK_FULL                       = 17
           DP_TIMEOUT                      = 18
           FILE_NOT_FOUND                  = 19
           DATAPROVIDER_EXCEPTION          = 20
           CONTROL_FLUSH_ERROR             = 21
           OTHERS                          = 22
        IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
        ENDIF.

  • Possible to read/ write word files using Java?

    I'm planning to write a Java application that can read an MS word document, extract something (including mathematics equations created with the equation editor) from the document and write it to another word document.
    Is it possible to do this?
    Can anyone give me some idea?
    Any idea is much appreciated :)

    I think I may have misunderstood your question, but in case I didn't and you find this helpful, following is the code to read a word doc, replace certain strings, then write it out as a new doc.
    import java.io.*;
    public class Copy {
         public static String endResult;
         public static void main(String[] args) {
              String oldAuthor = "Samuel Foote";
              String newAuthor = "New Author";
              String oldDate = "1720-1777";
              String newDate = "1975 -- ";
          try {
              File inputFile = new File("C:\\document.doc");
              BufferedReader input = null;
              input = new BufferedReader(new FileReader(inputFile));
              StringBuffer contents = new StringBuffer();
              String line = null;
              while ((line = input.readLine()) != null){
                   contents.append(line);
                   contents.append(System.getProperty("line.separator"));          
              String text = contents.toString();
    //     Replace the author and the dates
              Copy y = new Copy();
              y.replace(text, oldAuthor, newAuthor);
              text = endResult;
              y.replace(text, oldDate, newDate);
    //     Copy the new, improved text to another file     //
              Copy z = new Copy();
              z.finalReplace(text);
              input.close();
         catch (FileNotFoundException ex) {
              ex.printStackTrace();
         catch (IOException ex){
              ex.printStackTrace();
         String replace(String text, String oldSubstring, String newSubstring) {
    //          Search the text for a string, then replace it //
              int fromIndex = 0;
              int e = 0;
              StringBuffer sb = new StringBuffer();
              while ((e = text.indexOf(oldSubstring, fromIndex)) >= 0) {
                   sb.append(text.substring(fromIndex, e));
                   sb.append(newSubstring);
                   fromIndex = e + oldSubstring.length();
              sb.append(text.substring(fromIndex));
              endResult = sb.toString();
              System.out.println("final string = " + sb);
              return sb.toString();
         String finalReplace (String args) throws IOException {
    //          Move the altered text to a new file  //
              File outputFile = new File("C:\\copied document.doc");
              FileWriter out = new FileWriter(outputFile);
              Writer output = null;
              try {
                   output = new BufferedWriter(new FileWriter(outputFile));
                   output.write(endResult);
              finally {
                   if (output != null) output.close();
                 return endResult;

  • I am receiving the data through the rs232 in labview and i have to store the data in to the word file only if there is a change in the data and we have to scan the data continuasly how can i do that.

    i am receiving the data through the rs232 in labview and i have to store the data in to the word or text file only if there is a change in the data. I have to scan the data continuasly. how can i do that. I was able to store the data into the text or word file but could not be able to do it.  I am gettting the data from rs232 interms of 0 or 1.  and i have to print it only if thereis a change in data from 0 to 1. if i use if-loop , each as much time there is 0 or 1 is there that much time the data gets printed. i dont know how to do this program please help me if anybody knows the answer

    I have attatched the vi.  Here in this it receives the data from rs232 as string and converted into binery. and indicated in led also normally if the data 1 comes then the led's will be off.  suppose if 0 comes the corresponding data status is wrtten into the text file.  But here the problem is the same data will be printed many number of times.  so i have to make it like if there is a transition from 1 to o then only print it once.  how to do it.  I am doing this from few weeks please reply if you know the answer immediatly
    thanking you 
    Attachments:
    MOTORTESTJIG.vi ‏729 KB

  • Issue regarding open word file and read only mode using c# & MS-word interop

    i am programmatically open a word file for search and highlight keyword. my routine is working fine. the problem is when i am opening the file programmatically then a dialog come and ask me to open file in read only mode. the dialog look like below one
    actually i do not want to open the file in read only mode because people can open and like to change and save. so guide me what i can do to not to open the file in read only mode.
    here is my full code. just have a look and tell me what is wrong in my code or tell me any trick as a result i can open the file not in read only mode. here is my code.
    private void button1_Click(object sender, EventArgs e)
                object fileName = "";
                string filePath = "";
                string strSaveasPath = "";
                DialogResult result = openFileDialog1.ShowDialog();
                if (result == DialogResult.OK)
                    fileName = openFileDialog1.FileName;
                    //strSaveasPath = Path.GetDirectoryName(path.ToString());
                //fileName = "Z:\\C0000000003.doc";
                List<string> _list = new List<string>();
                _list.Add("tridip");
                _list.Add("arijit");
                //object fileName = "D:\\CVArchievePath\\C0000000001.doc";
                object textToFind = "test";
                object readOnly = false;
                Word.Application word = new Word.Application();
                Word.Document doc = new Word.Document();
                object missing = Type.Missing;
                try
                    doc = word.Documents.Open(ref fileName, ref missing, ref readOnly,
                                              ref missing,
    ref missing, ref missing,
                                              ref missing,
    ref missing, ref missing,
                                              ref missing,
    ref missing, ref missing,
                                              ref missing,
    ref missing, ref missing,
                                              ref missing);
                    doc.Activate();
                    object matchPhrase = false;
                    object matchCase = false;
                    object matchPrefix = false;
                    object matchSuffix = false;
                    object matchWholeWord = false;
                    object matchWildcards = false;
                    object matchSoundsLike = false;
                    object matchAllWordForms = false;
                    object matchByte = false;
                    object ignoreSpace = false;
                    object ignorePunct = false;
                    object highlightedColor = Word.WdColor.wdColorGreen;
                    object textColor = Word.WdColor.wdColorLightOrange;
                    object missingp = false;
                    Word.Range range = doc.Range();
                    foreach (string line in _list)
                        textToFind = line;
                        bool highlighted = range.Find.HitHighlight(ref textToFind,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing,
    ref missing);
                    System.Diagnostics.Process.Start(fileName.ToString());
                catch (Exception ex)
                    Console.WriteLine("Error : " + ex.Message);
                    //Console.ReadKey(true);
                finally
                    //doc.Close(missing, missing, missing);
                    if(doc!=null)
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                    if (word != null)
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(word);
                    word = null;
                    doc = null;
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

    I know it's a very old issue and I reached to this page looking for a solution. Finally, I have found a fix to this problem.
    The problem is that we create an instance of Word and do not close it correctly. This makes program believe that the file is already open and hence you're getting the respective message of file being locked by you.
    Set the visibility of your application to true and then when you close it both file and instance should close and you will not get the problem again.

  • How to print an Doc file(MS Word File)on a printer in JAVA

    Hi.I am Prakash.
    Folowing is the code that i have used to print an doc file on a printer. Problem is that , when i run this code it will provide me an printout of a doc file.,but not in well formate as the actual formate of the file. If any one tried this before plz help me.Thanks
    import java.lang.reflect.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics2D;
    import java.io.*;
    import javax.swing.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import javax.print.event.*;
    public class BasicPrint {
         JFrame frame;
         JButton btn;
         private boolean PrintJobDone = false;
         protected void MakeGui() {
              frame = new JFrame("PrintService");
              btn = new JButton("Cancel Print Job");
              btn.disable();
              frame.getContentPane().add(btn, BorderLayout.SOUTH);
              frame.pack();
              frame.setVisible(true);
         BasicPrint(String FileToPrint, String pMode) {
              try {
                   MakeGui();
                   File baseDir = new File("d:/doc");
    File outDir = new File(baseDir, FileToPrint);
                   // Open the image file
                   InputStream is = new BufferedInputStream(new FileInputStream(
                             outDir));
                   // Find the default service
                   DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
                   //DocFlavor flavor = new DocFlavor("application/msword", "java.io.InputStream");
                   //DocFlavor docFlavor = new DocFlavor("application/vnd.ms-word", "java.io.InputStream");
                   if (pMode != null && pMode.equalsIgnoreCase("PS"))
                        flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
                   else if (pMode != null && pMode.equalsIgnoreCase("PDF"))
                        flavor = DocFlavor.INPUT_STREAM.PDF;
                   else if (pMode != null && pMode.equalsIgnoreCase("JPG"))
                        flavor = DocFlavor.INPUT_STREAM.JPEG;
                   else if (pMode != null && pMode.equalsIgnoreCase("GIF"))
                        flavor = DocFlavor.INPUT_STREAM.GIF;
                   else if (pMode != null && pMode.equalsIgnoreCase("PNG"))
                        flavor = DocFlavor.INPUT_STREAM.PNG;
                   else if (pMode != null && pMode.equalsIgnoreCase("PCL"))
                        flavor = DocFlavor.INPUT_STREAM.PCL;
                   else if (pMode != null && pMode.equalsIgnoreCase("RAW"))
                        flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
                   else if (pMode != null && pMode.equalsIgnoreCase("TXT16"))//****                                   *********
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16;
                        System.out.println("****ACTIVE***");
                   else if (pMode != null && pMode.equalsIgnoreCase("TXTBE"))//****
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16BE;
                   else if (pMode != null && pMode.equalsIgnoreCase("TXTHOST"))//***
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST;
                   else if (pMode != null && pMode.equalsIgnoreCase("TXT8"))
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_8;
                   else if (pMode != null && pMode.equalsIgnoreCase("TXTASCI"))
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII;
                   else if(pMode != null && pMode.equalsIgnoreCase("TXTLE"))
                        flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_16LE;                                        //*******
                   else if(pMode != null && pMode.equalsIgnoreCase("SEVICE"))
                        flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
                   String type = flavor.getMediaType();
                   System.out.println("Type ="+ type);
                   //IMPRIMIR prakashCV.doc TXT text/plain; charset="utf-16le"; class="java.io.InputStream"
                   System.err.println("* IMPRIMIR " + FileToPrint + " " + pMode + " "
                             + flavor);
                   PrintService dservice = PrintServiceLookup
                             .lookupDefaultPrintService();
                   PrintService[] services = PrintServiceLookup.lookupPrintServices(
                             flavor, null);
                   if (services == null || services.length < 1)
                        services = PrintServiceLookup.lookupPrintServices(null, null);
                   PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                   aset.add(new Copies(1));
                   aset.add(OrientationRequested.PORTRAIT);
                   // aset.add(MediaTray.MAIN);
                   aset.add(Sides.ONE_SIDED);
                   aset.add(MediaSizeName.ISO_A4);
                   PrintService service = ServiceUI.printDialog(
                             (GraphicsConfiguration) null, 60, 60, services,
                             (PrintService) dservice, (DocFlavor) flavor, aset);
                   if (service != null) {
                        // Create the print job
                        final DocPrintJob job = service.createPrintJob();
                        Doc doc = new SimpleDoc(is, flavor, null);
                        // Monitor print job events; for the implementation of
                        // PrintJobWatcher,
                        PrintJobWatcher pjDone = new PrintJobWatcher(job);
                        if (job instanceof CancelablePrintJob) {
                             btn.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       CancelablePrintJob cancelJob = (CancelablePrintJob) job;
                                       try {
                                            cancelJob.cancel();
                                       } catch (PrintException e) {
                                            // Possible reason is job was already finished
                             btn.enable();
                        try {
                             // Print it
                             job.print(doc, (PrintRequestAttributeSet) aset);
                        } catch (PrintException e) {
                             e.printStackTrace();
                        System.err.println("* Impresion Realizada - Esperando ..");
                        // Wait for the print job to be done
                        pjDone.waitForDone();
                   // It is now safe to close the input stream
                   is.close();
              } catch (IOException e) {
                   e.printStackTrace();
              } catch (Exception e) {
                   e.printStackTrace();
              } finally {
                   try {
                        synchronized (BasicPrint.this) {
                             PrintJobDone = true;
                             BasicPrint.this.notify();
                   } catch (Exception e) {
                        e.printStackTrace();
         public synchronized void waitForDone() {
              try {
                   while (!PrintJobDone) {
                        wait();
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              try {
                   //args[0]="t";
                   //args[1]="rr";
    //               if (args.length < 1) {
    //                    System.err.println("\nSintaxis:\n\n java BasicPrint FileToPrint [pMode]\n");
    //                    System.exit(0);
                   BasicPrint bp = null;
                   //if (args.length < 2){
                        //bp = new BasicPrint(args[0], null);
                   //}else{
                        //bp = new BasicPrint(args[0], args[1]);
                        bp = new BasicPrint("prakashCV.doc","SEVICE");                                                       //****/***
                   bp.waitForDone();
                   System.exit(0);
              } catch (Exception e) {
                   e.printStackTrace();
         class PrintJobWatcher {
              // true iff it is safe to close the print job's input stream
              boolean done = false;
              int lastEvent = 0;
              PrintJobWatcher(DocPrintJob job) {
                   // Add a listener to the print job
                   job.addPrintJobListener(new PrintJobAdapter() {
                        public void printJobRequiresAttention(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err
                                       .println("* La impresora requiere de su Atencion ! * "
                                                 + pje);
                             // allDone();
                        public void printDataTransferCompleted(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err
                                       .println("* Transferencia de datos a la impresora OK. * "
                                                 + pje);
                             // allDone();
                        public void printJobCanceled(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err.println("* Trabajo de impresion CANCELADO ! * "
                                       + pje);
                             allDone();
                        public void printJobCompleted(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err.println("* Impresion completa OK. * " + pje);
                             allDone();
                        public void printJobFailed(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err.println("* ERROR en la Impresion ! * " + pje);
                             // allDone();
                        public void printJobNoMoreEvents(PrintJobEvent pje) {
                             lastEvent = pje.getPrintEventType();
                             System.err
                                       .println("* No mas eventos de impresion * " + pje);
                             allDone();
                        void allDone() {
                             synchronized (PrintJobWatcher.this) {
                                  done = true;
                                  PrintJobWatcher.this.notify();
              /** Description of the Method */
              public synchronized void waitForDone() {
                   try {
                        while (!done) {
                             wait();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
    }

    Hi Maxpkh
    Do you mean attachment? You can't do that with free Adobe Reader you need Acrobat to do this.
    ~Deepak

Maybe you are looking for