我正在尝试读取文件的内容,例如 .txt、.doc 等,但由于某种原因,如果它不是 .txt 文件,它仅显示特殊符号/字符。
例如,如果我有一个文本文件并打印出内容,其中有“hello world”,它将打印出“hello world”。
但是,如果它是包含“hello world”的 Word 文档,那么它会显示类似“ê@~u©Ë#Έ~sñî‚Y‡G,óãe©Ré_?ê7¥Å”的内容
我希望它只读取任何类型的 Word 文档或文本文件的“普通字符”。这是我所拥有的:
private void openFile(){
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();//chooser is a JFileChooser
try {//read the files contents and display it as the current pages text
BufferedReader reader = new BufferedReader(new FileReader(file));
String textInFile = "", line;
while ((line = reader.readLine()) != null) {
textInFile += line;
}
editor.setText(textInFile);//display the text to a JTextPane named editor
} catch (Exception e1) {
}
}
}
为什么我被否决了?
最佳答案
这是因为 doc
文件没有编码为文本,而这是 BufferedReader
处理的内容。您需要使用 Apache POI 等库来解码该文件类型。
https://poi.apache.org/document/docoverview.html
关于java - BufferedReader 不显示文件中的正常字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33725144/