How to Work with Documents in Java

How to Work with Documents in Java

Aspose.Words FOSS for Java opens, reads, and merges Word documents in plain Java, without Microsoft Word. This guide uses Maven Central to get the library and shows two tasks with the Document class: reading the text of a file and merging two files.

Step-by-Step Guide

Step 1: Install the Package

Add the package to your build. Your build tool also downloads the ten ordinary libraries the package depends on.

<dependency>
  <groupId>org.aspose</groupId>
  <artifactId>aspose-words-foss</artifactId>
  <version>26.3.0</version>
</dependency>

Step 2: Import the Classes

Every class is in the com.aspose.words package. The examples below start with import com.aspose.words.*;, which is enough for everything on this page. The library needs Java 8 or later.


Step 3: Open a Document and Read Its Text

Pass a file name to the Document constructor. getText, inherited from Node, gets the text of this node and of all its children. The same recipe saves the document as plain text and as Markdown by using those file extensions.

import com.aspose.words.*;

Document doc = new Document("input.docx");
String text = doc.getText();           // fast, includes control chars
doc.save("input.txt");                 // or: clean plain-text export
doc.save("input.md");                  // or: Markdown, preserves structure

Step 4: Merge Two Documents

appendDocument appends the second document to the end of the first. ImportFormatMode.KEEP_SOURCE_FORMATTING copies all required styles to the destination document and generates unique style names if needed.

import com.aspose.words.*;

Document main = new Document("main.docx");
Document appendix = new Document("appendix.docx");
main.appendDocument(appendix, ImportFormatMode.KEEP_SOURCE_FORMATTING);
main.save("combined.docx");

Common Issues and Fixes

The compiler reports cannot find symbol for Document. The com.aspose.words package is not imported. Add import com.aspose.words.*; at the top of the file.

Opening a document throws a FileNotFoundException. The message reads “Can’t find file” followed by the file name. Check the path, which is relative to the directory the program runs in.

The compiler reports an unreported exception. The Document constructors and Document.save declare throws Exception. Declare it on the calling method or catch it.

Frequently Asked Questions

Do I need Microsoft Word installed?

No. The examples ran without Word.

Which classes should I start with?

Document holds a whole document and DocumentBuilder writes content into it.

Which Java versions work?

The examples were run on Java 8, 17 and 21.

See Also