我正在使用以下方法从文件中读取:
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 控件 HTMLEditor 中。这有效,但所有读取的文本都插入到一行中,这意味着原始文件中的换行符被忽略。
有没有人知道如何解决这个问题?
提前致谢!
问候
最佳答案
如果源文件是 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); }
}
关于JavaFX HTML 编辑器 : Text is in one single line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26143471/