问题
My goal is to read from a rich text formatted file and then display it's contents exactly how they appear with formatting in a JavaFX TextArea. I have already completed this with a plain text file (ANSI encoded). When I try to read from an rtf file it displays all the text as well as the formatting symbols. Is there a function that interprets these formatting symbols as it scans it in? It's been difficult trying to find an answer to this, so any help is greatly appreciated!
You can see my current file reading function from my Controller class:
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
And this is the output to my text area: {\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} {*\generator Riched20 6.2.9200}\viewkind4\uc1 \pard\sl240\slmult1\f0\fs22\lang9 This is a rtf document 12 3\par \tab Tab\par \b This is bold\par }
When I want this to be output:
This is a rtf document 12 3
___Tab
This is bold
来源:https://stackoverflow.com/questions/28573275/how-to-read-rtf-file-and-display-in-javafx