In daily document management, file format conversion is a common and necessary task. Developers often need to convert between different file types, especially from plain text (TXT) to Word (DOC or DOCX). While TXT files are lightweight and widely used, Word documents support rich text formatting and layout, making them ideal for professional document editing and sharing.
This article provides a comprehensive guide to efficiently converting TXT files to Word in a Java environment. It covers basic formatting during conversion and includes examples for batch processing—perfect for enterprises or anyone handling large volumes of documents.
Why Convert TXT to Word?
Converting TXT files to Word offers several advantages:
Enhanced Editability
TXT files contain plain text without support for fonts, sizes, or paragraph formatting. Word documents, however, allow rich text formatting and layout options.Improved Compatibility
Word files can be opened in a wide range of word processors, including Microsoft Word, LibreOffice, and others.Easy Sharing and Archiving
After conversion, Word documents can be easily printed, shared, or exported to PDF for broader use.
Prerequisites
Before starting, ensure your development environment is properly configured:
Java Development Kit (JDK)
Install JDK 1.6 or higher.Spire.Doc for Java
This library handles document conversions. Download it from the E-iceblue official site or add it via Maven/Gradle.
Maven Example:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>13.12.2</version>
</dependency>
</dependencies>
Gradle Example:
repositories {
maven {
url "https://repo.e-iceblue.com/nexus/content/groups/public/"
}
}
dependencies {
implementation 'e-iceblue:spire.doc:13.12.2@jar'
}
Method 1: Convert a Single TXT File to Word
For small-scale tasks, such as converting personal notes, logs, or documentation to Word for printing or archiving, the simplest approach is to load the TXT file and save it as a Word document using Spire.Doc.
Example Code:
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class ConvertTextToWord {
public static void main(String[] args) {
// Create a Document object
Document txt = new Document();
// Load the TXT file
txt.loadFromFile("input.txt");
// Save as Word document
txt.saveToFile("output.docx", FileFormat.Docx);
// Release resources
txt.dispose();
System.out.println("TXT to Word conversion completed!");
}
}
Method 2: Batch Convert Multiple TXT Files to Word
When dealing with large volumes of TXT files, converting them one by one is inefficient. For example, a department may need to organize hundreds of TXT files into Word format. Using Java to iterate over a folder and perform batch conversion greatly improves efficiency.
Example Code:
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import java.io.File;
public class BatchTxtToWord {
public static void main(String[] args) {
String inputFolder = "path/to/txt/files";
String outputFolder = "path/to/word/output";
File folder = new File(inputFolder);
File[] txtFiles = folder.listFiles((dir, name) -> name.endsWith(".txt"));
if (txtFiles != null) {
for (File file : txtFiles) {
try {
Document doc = new Document();
doc.loadFromFile(file.getAbsolutePath());
String outputPath = outputFolder + File.separator + file.getName().replace(".txt", ".docx");
doc.saveToFile(outputPath, FileFormat.Docx);
doc.dispose();
System.out.println("Converted successfully: " + file.getName() + " -> " + outputPath);
} catch (Exception e) {
System.out.println("Conversion failed: " + file.getName() + ", Error: " + e.getMessage());
}
}
} else {
System.out.println("No TXT files found!");
}
}
}
Method 3: Convert TXT to Word with Formatting
For professional documents like reports, course materials, or project files, plain conversion is not enough. Proper formatting ensures a professional appearance, with consistent fonts, sizes, colors, and paragraph alignment.
Example Code:
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;
import java.awt.Color;
public class TxtToWordFormatted {
public static void main(String[] args) {
// Load TXT file
Document doc = new Document();
doc.loadFromFile("input.txt");
// Iterate through all paragraphs
for (Section section : doc.getSections()) {
for (Paragraph para : section.getParagraphs()) {
// Center-align paragraph
para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
// Set font, size, and color for each text range
for (DocumentObject obj : para.getChildObjects()) {
if (obj instanceof TextRange) {
TextRange range = (TextRange) obj;
range.getCharacterFormat().setFontName("Microsoft YaHei");
range.getCharacterFormat().setFontSize(12);
range.getCharacterFormat().setTextColor(Color.BLUE);
}
}
}
}
// Save as Word document
doc.saveToFile("output.docx", FileFormat.Docx);
// Release resources
doc.dispose();
}
}
Key Considerations
To ensure the generated Word documents display correctly and maintain proper formatting, keep these points in mind:
- Character Encoding: Use UTF-8 for TXT files to avoid garbled text, especially with Chinese characters.
- Font Compatibility: Choose fonts compatible across operating systems to prevent display issues.
- File Paths: Avoid Chinese or special characters in file paths to ensure cross-platform execution.
-
Resource Management: Always call
dispose()after conversion to release document objects and prevent memory leaks.
Conclusion
This guide demonstrates three effective ways to convert TXT files to Word in Java:
- Single File Conversion: Ideal for processing a few TXT files quickly.
- Batch Conversion: Efficient and automated, perfect for enterprise or large-scale document processing.
- Formatted Conversion: Customize fonts, sizes, colors, and paragraph styles for professional-looking documents.
Choose the method that best fits your scenario and streamline your TXT to Word conversion process.
Top comments (0)