Solved

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

Posted on 2002-04-04
19
229 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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
 

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
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…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

688 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