Solved

How do I display the contents of a MS-Word document in Java?

Posted on 2002-04-04
19
222 Views
Last Modified: 2010-03-31
Hi

This is the code (slightly modified) that I got from a book.



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FileBrowser extends JFrame
{
  JTextArea text = new JTextArea(20, 64);
  JButton button1 = new JButton( "FileDialog");


public static void main (String [] args)
{
  new FileBrowser();
}

public FileBrowser()
{

  Container c = getContentPane();
     text.setFont(new Font("Monospaced", Font.BOLD, 18));
     c.add(text,  "Center");
        c.add(button1,  "South");

button1.addActionListener(new ActionListener()
{
 public void actionPerformed(ActionEvent evt)
     {
      final FileDialog fd =
               new FileDialog( FileBrowser.this,
                              "Choose a file",
                              FileDialog.LOAD);
          fd.setFile("*.doc");
          fd.show();
         
          text.setText("");
          text.append("\nDirectory=" + fd.getDirectory());
          text.append("\nFile=" + fd.getFile());
}
});

pack();
show();

}
}

The program has a textfield above and a button below to browse thru the files. When the file is selected, how do I display the contents into the textfield?

I appreciate anybody`s help here.

Thanks

Faizal

0
Comment
Question by:faizal
  • 10
  • 9
19 Comments
 
LVL 1

Expert Comment

by:jose_tijo
ID: 6920151
try {
                                   //Open an InputStream for the file
                                   FileInputStream wordFile = new FileInputStream (strDirectory + files[i]);
                                   out = "";
                                   //Read char by char and check for printable and add to a string
                                   byteArray = new byte[wordFile.available()];
                                   wordFile.read(byteArray);
                                   int j = 0;
                                   while(j < byteArray.length) {
                                        c = (char)byteArray[j];
                                        tempChar = new Character(c);
                                        //Checks for printable
                                        if (tempChar.getNumericValue(c) <= 35 && tempChar.getNumericValue(c) >= 9 || tempChar.isSpaceChar(c)) {
                                             out += tempChar.toString();
                                        }
                                        j++;
                                   }
                                         
                                   System.out.println(out);
                                   System.out.println("*****************************************************************************************");
                              }catch (Exception e) {
                                   System.out.println("Read Failed...." + e);
                               }
0
 

Author Comment

by:faizal
ID: 6920459
Hi

Where do I put in the code? I tried to put in after the text.append() but there is still an error.

Rgds

Faizal
0
 
LVL 1

Expert Comment

by:jose_tijo
ID: 6920524
Hi
   You set the textbox value to "out" the variable in my program

Tijo Jose
0
 

Author Comment

by:faizal
ID: 6920606
I`m not too sure what you mean by setting the textbox value to "out". How do I set the value?

Faizal
0
 
LVL 1

Expert Comment

by:jose_tijo
ID: 6924590
Hi
   After you execute my piece of code you get the text content of the file in the variable "out".

You can use the following after that
      text.setText(out);

Still you are confused you send me your entire .java file and i'll correct it and send back to you

Tijo Jose

0
 

Author Comment

by:faizal
ID: 6924852
Hi

Ok, I`ll send you my entire .java file. What is your email address? The java code is already written above.

Faizal
0
 
LVL 1

Expert Comment

by:jose_tijo
ID: 6925070
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FileBrowser extends JFrame
{
 JTextArea text = new JTextArea(20, 64);
 JButton button1 = new JButton( "FileDialog");
 FileInputStream wordFile;
 String out;
 byte[] byteArray;
 char ch;
 Character tempChar = new Character('t');


public static void main (String [] args)
{
 new FileBrowser();
}

public FileBrowser()
{

 Container c = getContentPane();
    text.setFont(new Font("Monospaced", Font.BOLD, 18));
    c.add(text,  "Center");
       c.add(button1,  "South");

button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
    {
     final FileDialog fd =
              new FileDialog( FileBrowser.this,
                             "Choose a file",
                             FileDialog.LOAD);
         fd.setFile("*.doc");
         fd.show();
         

          try {
     //Open an InputStream for the file
     wordFile = new FileInputStream (fd.getDirectory() + fd.getFile());

     out = "";
     //Read char by char and check for printable and add to a string
     byteArray = new byte[wordFile.available()];
     wordFile.read(byteArray);
     int j = 0;
     while(j < byteArray.length) {
        ch = (char)byteArray[j];
        tempChar = new Character(ch);
        //Checks for printable
        if (tempChar.getNumericValue(ch) <= 35 && tempChar.getNumericValue(ch)     >= 9 || tempChar.isSpaceChar(ch)) {
               out += tempChar.toString();
       }
       j++;
    }


}catch (Exception e) {
     System.out.println("Read Failed...." + e);
 }


      text.setText("");
      text.append("\nDirectory=" + fd.getDirectory());
      text.append("\nFile=" + fd.getFile());
      text.append("\n" + out);    
}
});

pack();
show();

}
}
0
 

Author Comment

by:faizal
ID: 6927486
Hi

It works ok but the document being displayed is continuous on one line. How do I display and divide the document into lines?

Faizal
0
 
LVL 1

Expert Comment

by:jose_tijo
ID: 6927620
Hi
  Here is the updated version. This will divide into seperate lines. I have added these lines

text.setLineWrap(true);    
text.setWrapStyleWord(true);

Tijo


import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FileBrowser extends JFrame
{
 JTextArea text = new JTextArea(20, 64);
 JButton button1 = new JButton( "FileDialog");
 FileInputStream wordFile;
 String out;
 byte[] byteArray;
 char ch;
 Character tempChar = new Character('t');


public static void main (String [] args)
{
 new FileBrowser();
}

public FileBrowser()
{

 Container c = getContentPane();
    text.setFont(new Font("Monospaced", Font.BOLD, 18));
    c.add(text,  "Center");
       c.add(button1,  "South");

button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
    {
     final FileDialog fd =
              new FileDialog( FileBrowser.this,
                             "Choose a file",
                             FileDialog.LOAD);
         fd.setFile("*.doc");
         fd.show();
         

          try {
     //Open an InputStream for the file
     wordFile = new FileInputStream (fd.getDirectory() + fd.getFile());

     out = "";
     //Read char by char and check for printable and add to a string
     byteArray = new byte[wordFile.available()];
     wordFile.read(byteArray);
     int j = 0;
     while(j < byteArray.length) {
        ch = (char)byteArray[j];
        tempChar = new Character(ch);
        //Checks for printable
        if (tempChar.getNumericValue(ch) <= 35 && tempChar.getNumericValue(ch)     >= 9 || tempChar.isSpaceChar(ch)) {
               out += tempChar.toString();
       }
       j++;
    }
                                       
     //System.out.println(out);
     //System.out.println("*****************************************************************************************");

}catch (Exception e) {
     System.out.println("Read Failed...." + e);
 }
      text.setLineWrap(true);    
      text.setWrapStyleWord(true);    
      text.setText("");
      text.append("\nDirectory=" + fd.getDirectory());
      text.append("\nFile=" + fd.getFile());
      text.append("\n" + out);    
}
});

pack();
show();

}
}
0
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!

 

Author Comment

by:faizal
ID: 6931244
Hi

It works ok. I can see the MS-Word document but is there a way to make the window scrollable?

Faizal
0
 
LVL 1

Accepted Solution

by:
jose_tijo earned 200 total points
ID: 6933276
Hi
  Try this. This will give you scrollbar also.

Tijo


/***Source: FileBrowser.java***/

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FileBrowser extends JFrame {
 JTextArea text = new JTextArea(20, 64);
 JButton button1 = new JButton( "FileDialog");
 FileInputStream wordFile;
 String out;
 byte[] byteArray;
 char ch;
 Character tempChar = new Character('t');


public static void main (String [] args)
{
 new FileBrowser();
}

public FileBrowser()
{

    Container c = getContentPane();
    JScrollPane areaScrollPane = new JScrollPane(text);
    areaScrollPane.setVerticalScrollBarPolicy(
                       JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    text.setFont(new Font("Monospaced", Font.BOLD, 18));
    c.add(areaScrollPane,  "Center");
    c.add(button1,  "South");

button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
    {
     final FileDialog fd =
              new FileDialog( FileBrowser.this,
                             "Choose a file",
                             FileDialog.LOAD);
         fd.setFile("*.doc");
         fd.show();
         

     try {
     //Open an InputStream for the file
     wordFile = new FileInputStream (fd.getDirectory() + fd.getFile());

     out = "";
     //Read char by char and check for printable and add to a string
     byteArray = new byte[wordFile.available()];
     wordFile.read(byteArray);
     int j = 0;
     while(j < byteArray.length) {
        ch = (char)byteArray[j];
        tempChar = new Character(ch);
        //Checks for printable
        if (tempChar.getNumericValue(ch) <= 35 && tempChar.getNumericValue(ch)     >= 9 || tempChar.isSpaceChar(ch)) {
               out += tempChar.toString();
       }
       j++;
    }
                                       
     //System.out.println(out);
     //System.out.println("*****************************************************************************************");

}catch (Exception e) {
     System.out.println("Read Failed...." + e);
 }
     text.setLineWrap(true);    
     text.setWrapStyleWord(true);    
     text.setText("");
        text.setAutoscrolls(true);
     text.append("\nDirectory=" + fd.getDirectory());
     text.append("\nFile=" + fd.getFile());
     text.append("\n" + out);    
}
});

pack();
show();

}
}
0
 

Author Comment

by:faizal
ID: 6933369
Hi

I forgot to ask something. The scrolling bar works ok but when the text is displayed, why is there meaningless words being displayed also?

Faizal
0
 
LVL 1

Expert Comment

by:jose_tijo
ID: 6933526
hi
   ie. the formatting detalis in the word document

Tijo
0
 

Author Comment

by:faizal
ID: 6939928
Thanks for your help.

Faizal
0
 

Author Comment

by:faizal
ID: 6955680
Hi

I would like to know the part about outputing the data char by char. What does it mean by printable? Maybe, you can explain this part of the code to me?

Thanks

Faizal
0
 
LVL 1

Expert Comment

by:jose_tijo
ID: 6955706
Hi
  I was out of station thats why delay in replying. I'm checking for printable to avoid junk characters to be displayed. Word maintains the format in a very complex format. thats why

Tijo
0
 

Author Comment

by:faizal
ID: 6955720
Hi

Ok, now I understand the printable now but I would like to know the output part, how they are being displayed. The code is below.

Also, the part of checking printable, could you explain the code to me?




byteArray = new byte[wordFile.available()];
    wordFile.read(byteArray);
    int j = 0;
    while(j < byteArray.length) {
       ch = (char)byteArray[j];
       tempChar = new Character(ch);
       //Checks for printable
       if (tempChar.getNumericValue(ch) <= 35 && tempChar.getNumericValue(ch)     >= 9 || tempChar.isSpaceChar(ch))
{
              out += tempChar.toString();
      }
      j++;
   }


Faizal
0
 
LVL 1

Expert Comment

by:jose_tijo
ID: 6964727
hi
   First of all i'm reading the word file into a byte array. After that i traverse throught that array character by character. i'm checking whether the numeric value of the character is between 9 & 35. also i check if it is a space. these are for normal characters. then i add that to a string and print it. thats all.

Tijo
0
 

Author Comment

by:faizal
ID: 6965614
Hi

I understand it now. Thanks.

Faizal
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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 if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

747 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

16 Experts available now in Live!

Get 1:1 Help Now