Reputation:
i am using the following method to read from a file:
public static StringBuilder read(String filepath) {
ByteBuffer buffer = ByteBuffer.allocate(1000000);
Path path = Paths.get(filepath);
StringBuilder content = null;
try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)) {
Future<Integer> fileResult = channel.read(buffer, 0);
while(!fileResult.isDone()) {
System.out.println("Reading in progress ...");
}
System.out.println("Bytes read: " + fileResult.get());
buffer.flip();
channel.close();
CharSequence sequence = Charset.defaultCharset().decode(buffer);
content = new StringBuilder(sequence);
} catch(IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return content;
}
I want to put the returned text into the JavaFX Control HTMLEditor. This works, but all the read text is insert in one line, means the line breaks from the original file are ignored.
Does anybody have any idea to fix this problem ?
Thanks in advance!
Greetz
Upvotes: 3
Views: 1697
Reputation: 159416
If the source file is an html file it will already of html encoded breaks and paragraph marks (e.g. <br>
or <p>
elements) in it.
If the source file is not an html file, don't try to display it in an HTMLEditor, use a TextArea or something like that instead.
Anyway if you decide to go ahead and load your text file in the html editor, here is some sample code. What it does is mark the loaded text as pre-formatted, by surrounding it with <pre>
tags, that way any whitespace and new lines in the input text is preserved in the HTMLEditor display:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;
import java.net.*;
import java.nio.file.*;
public class HTMLEditorLineDisplay extends Application {
private static final String TEXT_LOCATION =
"http://www.textfiles.com/etext/AUTHORS/SHAKESPEARE/shakespeare-life-54.txt";
private StringBuilder textBuilder = new StringBuilder();
@Override
public void init() throws Exception {
// sample data from the internet placed in a temporary file.
Path tmpFile = Files.createTempFile("html-editor-text", ".txt");
Files.copy(
new URL(TEXT_LOCATION).openStream(),
tmpFile,
StandardCopyOption.REPLACE_EXISTING
);
// read lines from a file, appending a pre-formatting tag.
textBuilder.append("<pre>");
Files.lines(tmpFile)
.forEach(
line -> textBuilder.append(line).append("\n")
);
textBuilder.append("</pre>");
Files.delete(tmpFile);
}
@Override public void start(Stage stage) {
// load pre-formatted text into the html editor.
HTMLEditor editor = new HTMLEditor();
editor.setHtmlText(textBuilder.toString());
textBuilder = new StringBuilder();
stage.setScene(new Scene(editor));
stage.show();
}
public static void main(String[] args) { launch(args); }
}
Upvotes: 3