DEV Community

Jeremy K.
Jeremy K.

Posted on

Java: Word to TXT Conversion

In routine software development, converting Word documents to plain text is a frequently encountered requirement, commonly seen in use cases such as content retrieval, text analysis, data ingestion, and batch document preprocessing. Rather than parsing Word's binary format directly, leveraging a mature document-processing library can significantly reduce development effort. This article demonstrates how to quickly convert Word (DOC/DOCX) files to TXT using the Free Spire.Doc for Java library, complete with code examples and key considerations.


1. Common Approaches

Word documents are essentially structured files containing rich content—styles, formatting, images, tables, and more. The core objective of plain-text extraction is to strip away formatting while preserving the readable textual content.

There are generally several technical paths to achieve Word-to-TXT conversion:

  • Parsing with Apache POI: Offers high flexibility but requires handling format differences across various Word versions and involves a larger code footprint.
  • Calling Office automation interfaces: Depends on a local Office installation, which incurs high server deployment and maintenance costs.
  • Using third-party document libraries: Provides well-designed, high-level APIs, operates without Office dependencies, and significantly boosts development productivity.

Free Spire.Doc for Java falls into the third category. It runs independently without requiring Microsoft Office, offers solid support for both DOC and DOCX formats, and features an intuitive API design—making it a practical choice for quickly implementing conversion functionality.


2. Maven Dependency Configuration

Add the official repository and the free-version dependency to your pom.xml:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc.free</artifactId>
    <version>14.3.1</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

3. Core Implementation for Word-to-TXT Conversion

The conversion process is straightforward and concise, boiling down to just three core steps: Load → Save → Release.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class WordToTxtConverter {
    public static void main(String[] args) {
        // 1. Create a Document instance
        Document doc = new Document();

        // 2. Load the Word document (supports .doc and .docx)
        doc.loadFromFile("C:\\input\\sample.docx");

        // 3. Save as TXT format
        doc.saveToFile("C:\\output\\converted.txt", FileFormat.Txt);

        // 4. Release resources
        doc.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

The saveToFile method preserves paragraph breaks, and the overall output structure corresponds faithfully to the original paragraph order.


4. Advanced Usage and Batch Processing

Batch Conversion

To convert multiple Word documents in batch, combine the conversion logic with directory traversal:

import java.io.File;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class BatchWordToTxt {
    public static void main(String[] args) {
        String inputDir = "C:\\word_files\\";
        String outputDir = "C:\\txt_output\\";

        File folder = new File(inputDir);
        File[] files = folder.listFiles((dir, name) -> 
            name.endsWith(".doc") || name.endsWith(".docx"));

        if (files != null) {
            for (File wordFile : files) {
                Document doc = new Document();
                doc.loadFromFile(wordFile.getAbsolutePath());

                String outputPath = outputDir + 
                    wordFile.getName().replaceAll("\\.docx?$", ".txt");
                doc.saveToFile(outputPath, FileFormat.Txt);
                doc.dispose();

                System.out.println("Converted: " + wordFile.getName());
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Extracting Text Without Saving to a File

If you only need the text content for in‑memory processing—for example, to store it in a database—use the getText() method:

Document doc = new Document();
doc.loadFromFile("sample.docx");
String textContent = doc.getText();  // Retrieve plain text content
doc.dispose();
// Proceed with further processing on textContent
Enter fullscreen mode Exit fullscreen mode

5. Common Issues and Considerations

5.1 Free Version Limitations

The free edition imposes upper limits on the number of paragraphs and tables. It is well-suited for personal learning, small utility tools, and feature validation, but may not be appropriate for large-scale production use.

5.2 Encoding Issues

  • When using saveToFile to output TXT directly, the default encoding is UTF-8.
  • If your target system requires GBK encoding, you can switch the encoding format during the file-writing stage.

5.3 Resource Management

The Document object consumes memory resources. Always call dispose() after use to release them. In batch-processing scenarios, it is advisable to release resources immediately after each file to prevent OutOfMemoryError.

5.4 Handling of Non-Text Content

Since TXT does not support images, table borders, font styling, or other rich formatting, the following behavior applies after conversion:

  • Images are omitted and will not appear in the output.
  • Table content is converted to plain text in cell order, losing its original row/column structure.
  • Hyperlinks retain only the visible display text, not the underlying URLs.

If you need to preserve more formatting details, consider converting to intermediate formats such as HTML or Markdown.


The examples above show how to accomplish the core conversion logic with just a few lines of code. For scenarios that do not require deep customization of formatting, this approach offers low development costs and rapid integration, satisfying most text-extraction needs.

In real-world projects, it is recommended to perform a balanced evaluation based on document volume, concurrency, and formatting requirements. For small-scale batch processing, the free version is sufficient for a quick start. For production environments with high concurrency and large documents, further performance benchmarking and exploration of alternative solutions are strongly advised.

Top comments (0)