要实现Java读取txt文件内容并生成Word文档,你需要以下步骤:
步骤一:读取txt文件内容
- 创建一个File对象,用于表示要读取的txt文件;
- 创建一个BufferedReader对象,用于读取文件内容;
- 使用BufferedReader的readLine()方法逐行读取文件内容,把每一行的文本保存到一个字符串变量中。
以下是示例代码:
File file = new File("example.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
String content = stringBuilder.toString();
步骤二:生成Word文档
- 创建一个XWPFDocument对象,用于表示Word文档;
- 使用XWPFDocument的createParagraph()方法创建段落,使用createRun()方法创建文本;
- 把txt文件中的文本加入到Word文档中;
- 使用XWPFDocument的write()方法把文档保存到磁盘。
以下是示例代码:
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(content);
document.write(new FileOutputStream("example.docx"));
示例一:读取本地txt文件生成Word文档
import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
public class FileToWord {
public static void main(String[] args) throws IOException {
File file = new File("example.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
String content = stringBuilder.toString();
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(content);
document.write(new FileOutputStream("example.docx"));
bufferedReader.close();
}
}
示例二:读取网络txt文件生成Word文档
import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
import java.net.URL;
public class URLToWord {
public static void main(String[] args) throws IOException {
URL url = new URL("https://example.com/example.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
String content = stringBuilder.toString();
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(content);
document.write(new FileOutputStream("example.docx"));
bufferedReader.close();
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java如何实现读取txt文件内容并生成Word文档 - Python技术站