簡體   English   中英

文件讀取器IO讀取文本文件

[英]File Reader IO Reading Text Files

我有一個任務要求我從文本文件中讀取代碼。 有人知道我的代碼會出現什么問題嗎?

它不輸出文本本身,而是輸出額外的字符:

{\\ 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}

什么時候應該輸出這個:

全日空

下面是代碼:

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);
}
}

謝謝您的幫助!

文件閱讀器不會神奇地理解RTF格式,也不會神奇地刪除所有格式化標記。 它從文件中讀取字符,而不關心這些字符代表什么。

如果您希望能夠執行此操作,則需要RTF文檔解析器。 或者您需要使您的文件成為純文本文件,而不是RTF文檔。

編輯

看來你的文本文件不僅包含預期的四行,還包含其他代碼。

以前的內容

您確定您的文本文件僅包含這四個字符串並且沒有特殊格式嗎? 您可以檢查新創建的另一個文本文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM