D盘下有个文件abc.txt,请用Java实现读取该文件并把文件内容生成word文件
时间: 2024-04-29 14:22:30 浏览: 83
下面是Java代码实现:
```java
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
public class FileToWord {
public static void main(String[] args) throws IOException {
String filePath = "D:/abc.txt";
String wordPath = "D:/abc.docx";
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(readFileContent(inputStream));
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(wordPath);
document.write(outputStream);
outputStream.close();
}
public static String readFileContent(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
}
```
如上所示,我们可以首先定义输入文件路径和输出文档路径。然后,创建一个文件对象,使用Java文件输入流读取文件内容。接着,我们使用Apache POI库创建一个Word文档和段落,并在段落中添加从文件中读取的文本。最后,我们再创建一个Java文件输出流将Word文档输出到指定路径下的文件。
阅读全文