I have an assignment that asks me to read a code from a text file. Does anybody know what would be wrong with my code?

Instead of outputting the text itself it also outputs extra characters:

{\rtf1\ansi\ansicpg1252\cocoartf1187\cocoasubrtf390{\fonttbl\f0\fswiss\fcharset0 Helvetica;}{\colortbl;\red255\green255\blue255;}\margl1440\margr1440\vieww10800\viewh8400\viewkind0\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\f0\fs24 \cf0 ana\nan\stop\pots}

when it should just be outputting this:

ana

nan

stop

pots

Heres the code:

package anagram1;

import java.io.FileReader; //Access file systems and allows buffered reader
                        //to read
import java.io.BufferedReader; //Scanner

import java.util.Scanner;

public class Anagram1 {


public static void main(String[] args) throws Exception
{
    String path;
    Scanner prompt = new Scanner(System.in); 
    System.out.println("Enter file path.");
    path = prompt.nextLine();


    FileReader file = new FileReader(path);  //here is where the file path is inserted
    BufferedReader reader = new BufferedReader(file);


    String text = ""; //stores what is inside file
    String line = reader.readLine(); //keeps reading line after line of string given
    while (line != null)
    {
        text += line;
        line = reader.readLine();

    }

    System.out.println(text);
}
}

Thanks for the help!

有帮助吗?

解决方案 2

EDIT

It seems your text file contains not only the expected four lines but other code.

Former content

Are you sure your text file ONLY contains these four strings and is no special format? You could probably check with another text file you freshly created.

其他提示

A file reader doesn't magically understands the RTF format and doesn't magically strips all the formatting markup. It reads characters from a file, without caring about what these characters represent.

You need an RTF document parser if you want to be able to do that. Or you need to make your file a pure text file, and not an RTF document.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top