JavaFX HTML编辑器:文本在一行中

时间:2014-10-01 14:14:20

标签: java io javafx-8

我使用以下方法从文件中读取:

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

我想将返回的文本放入JavaFX Control HTMLEditor中。这有效,但所有阅读文字都插入一行,表示原始文件中的换行符忽略

有人有任何想法解决这个问题吗?

提前致谢!

格尔茨

1 个答案:

答案 0 :(得分:1)

如果源文件是html文件,则其中已经存在html编码的中断和段落标记(例如<br><p>元素)。

如果源文件不是html文件,请不要尝试在HTMLEditor中显示该文件,而是使用TextArea或类似内容。

无论如何,如果您决定继续在html编辑器中加载文本文件,这里有一些示例代码。它的作用是将加载的文本标记为预格式化,用<pre>标记包围它,这样输入文本中的任何空格和新行都保存在HTMLEditor显示中:

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