Java-在读取文本文件时忽略某些字符

Java-在读取文本文件时忽略某些字符,java,input,io,text-files,java.util.scanner,Java,Input,Io,Text Files,Java.util.scanner,我正在尝试读取包含以下内容的简单文本文件: 装载 比尔的豆子 1200 二十 十五 三十 退出 我需要逐行存储和打印内容。我使用以下代码执行此操作: String inputFile = "(file path here)"; try { Scanner input = new Scanner(inputFile); } catch (FileNotFoundException e) { e.printStackTrace(); }

我正在尝试读取包含以下内容的简单文本文件:

装载

比尔的豆子

1200

二十

十五

三十

退出

我需要逐行存储和打印内容。我使用以下代码执行此操作:

    String inputFile = "(file path here)";
    try {
        Scanner input = new Scanner(inputFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    String currentLine = "";
    while (!currentLine.equals("QUIT}")){
        currentLine = input.nextLine();
        System.out.println(currentLine);
    }
    input.close();
然而,输出非常混乱。我试图避免存储所有新行字符以及文本文件中未出现的任何其他内容。输出为:

{\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf540

{\fonttbl\f0\fmodern\fcharset0 Courier;}

{\colortbl;\red255\green255\blue255;}

\margl1440\margr1440\vieww9000\viewh8400\viewkind0

\deftab720

\pard\pardeftab 720\ql\qnatural

\f0\fs26\cf0加载\

比尔的豆子\

1200\

二十\

十五\

三十\

退出}


任何帮助都将不胜感激,谢谢

这看起来像是在读RTF文件,不是吗

否则,我发现使用以下结构阅读文本文件对我来说是最自然的:

        BufferedReader reader = new BufferedReader(
                                    new FileReader(new File("yourfile.txt")
                                );
        String text = null;

        // repeat until all lines is read
        while ((text = reader.readLine()) != null) {
            // do whatever with the text line
        }

由于这是一个RTF文件,请查看以下示例:

如果您坚持编写自己的RTF读取器,正确的方法是在其实现中扩展和处理RTF元数据。

只需将以下代码添加到类中,然后使用path参数调用它。它将所有行作为列表对象返回

public List<String> readStudentsNoFromText(String path) throws IOException {
            List<String> result = new ArrayList<String>();

            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream(new File(path));
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                System.out.println(strLine);
                result.add(strLine.trim());

            }
            //Close the input stream
            in.close();

            return result;
        }

看起来它不仅仅是一个简单的文本文件?那不是一个文本文件,那是一个rtf文件。在记事本或操作系统的等效工具中打开文件。您是否研究过使用RTF解析器获取文本?注意:System.out.printlncurrentLine;正在添加换行符。使用System.out.printcurrentLine;那么你的输入文件是JSON提要还是什么?那些东西是从哪里来的?我认为你的输入文本文件并不像你想象的那么简单。它实际上是一个RTF,我的程序在Mac上。但该程序最终将在带有文本文件的Windows计算机上运行。当我使用缓冲读取器时,我得到了完全相同的结果。当它在Windows机器上使用文本文件运行时,这些特殊字符会被忽略吗?这并不重要。问题是,您正试图读取具有结构的专有格式。所以,如果你这样做的话,这些特殊的角色就不会被忽略。以RTFEditorKit为例。我给答案添加了一个链接,让你开始。但是请记住,您必须以某种方式解析文件,因为它不是纯文本。