如何在JavaFX中读取RTF文件并显示

时间:2015-02-17 23:33:36

标签: javafx javafx-2 textarea javafx-8 rtf

我的目标是从富文本格式的文件中读取,然后准确显示它们在JavaFX TextArea中的格式化方式。我已经用纯文本文件(ANSI编码)完成了这个。当我尝试从rtf文件中读取时,它会显示所有文本以及格式符号。是否有一个函数在扫描时解释这些格式符号?试图找到答案很困难,所以非常感谢任何帮助!

您可以从我的Controller类中看到我当前的文件读取功能:

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Scanner;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;


public class Screen2Controller implements Initializable , ControlledScreen {

    ScreensController myController; 

   //read from file in Dropbox
   @FXML
   public void displayText() {
        try {
            //rtf reads text and format characters
            Scanner s = new Scanner(new File("C:/Users/EECSDept/Dropbox/EECS Hallway Display/Department Info/rtftest.rtf")).useDelimiter("\\s+");
            while (s.hasNext()) {
                dinfoTextArea.appendText(s.next() + " "); // read the next token
            }
        } 
        catch (FileNotFoundException ex) {
            System.err.println("File not found - check file path | "+ex);
        }

    } //end displaytext

    //must reference specific textarea with correct fxid
    @FXML TextArea dinfoTextArea;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        displayText(); //call file reading function
    }



    public void setScreenParent(ScreensController screenParent){
        myController = screenParent;
    }

    @FXML
    private void goToScreen1(ActionEvent event){
       //go home
       myController.setScreen(ScreensFramework.screen1ID);
    }

    @FXML
    private void goToProgram(ActionEvent event){
       myController.setScreen(ScreensFramework.programID);
    }

    @FXML
    private void goToMap(ActionEvent event){
       myController.setScreen(ScreensFramework.mapID);
    }


} //end screen2controller

这是我文本区域的输出: {\ rtf1 \ ansi \ ansicpg1252 \ deff0 \ nouicompat \ deflang1033 {\ fonttbl {\ f0 \ fnil \ fcharset0 Calibri;}} {* \ generator Riched20 6.2.9200} \ viewkind4 \ uc1 \ pard \ sl240 \ slmult1 \ f0 \ fs22 \ lang9这是一个rtf文件12 3 \ par \ tab Tab \ par \ b这是粗体\ par}

当我希望输出时:

这是rtf文件12 3

___标签

这是粗体

0 个答案:

没有答案