[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 236
  • Last Modified:

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

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
faizal
Asked:
faizal
  • 10
  • 9
1 Solution
 
jose_tijoCommented:
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
 
faizalAuthor Commented:
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
 
jose_tijoCommented:
Hi
   You set the textbox value to "out" the variable in my program

Tijo Jose
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.

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

Faizal
0
 
jose_tijoCommented:
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
 
faizalAuthor Commented:
Hi

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

Faizal
0
 
jose_tijoCommented:
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
 
faizalAuthor Commented:
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
 
jose_tijoCommented:
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
 
faizalAuthor Commented:
Hi

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

Faizal
0
 
jose_tijoCommented:
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
 
faizalAuthor Commented:
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
 
jose_tijoCommented:
hi
   ie. the formatting detalis in the word document

Tijo
0
 
faizalAuthor Commented:
Thanks for your help.

Faizal
0
 
faizalAuthor Commented:
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
 
jose_tijoCommented:
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
 
faizalAuthor Commented:
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
 
jose_tijoCommented:
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
 
faizalAuthor Commented:
Hi

I understand it now. Thanks.

Faizal
0

Featured Post

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!

  • 10
  • 9
Tackle projects and never again get stuck behind a technical roadblock.
Join Now