java - BufferedReader 不显示文件中的正常字符

标签 java file bufferedreader filereader

我正在尝试读取文件的内容,例如 .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/

相关文章:

java - 如何让扫描器循环直到它读取到所需的字符串?

windows - rust :来自 “file repository”结构的怪异行为

file - 我如何让 sed 'w' 命令知道文件名的结尾?

Android:为什么 BufferedReader 读取 EOF?

Java:获取输入整数数组的最有效方法

java - 套接字:BufferedReader readLine() block

java - 如何在 Spring MVC 中为某个类自定义 JSON

java - 在 Java 正则表达式中仅打印三位数字的量词

java - 有没有办法在 Apache PropertiesConfiguration 中使用占位符

ios - 我应该遵循 iOS 数据存储指南吗?